combine class instance into another instance in python? - python

I am in designing one "jigsaw puzzle" like tool to manage different water pipe like parts combination for fun.
I have different single parts type with different purpose(cooler, heater, purifier...)
Those parts with different interfaces size can be connected with each other (1/4 inch. 1/6 inch ....)
I want those parts can be stored in database and can be combined into a total new parts combination(randomly or purposely), but still can be considering as a function-able part.
Here is the initial thinking
class MetaInfo():
def __init__(self, name, intype,outtype,shape,serialno):
this.name = name
this.intype = intype
this.outtype = outtype
this.shape = shape
this.sn = serialno
def parts():
def __init__(self, meta):
this.meta = meta
def linkwith(self, part):
if part.meta.shape == this.meta.shape:
# make it simple, logical here is just same shape can be connected each other
return ??? # a new parts combination
else:
raise Error
m1 = MetaInfo("cooler", "hotwater", "coldwater", "1/4 inch round", "SN:11111" )
m2 = MetaInfo("heater", "coldwater", "hotwater", "1/4 inch round", "SN:22222" )
m3 = MetaInfo("purifier", "coldwater", "hotwater", "1/6 inch round", "SN:33333" )
a = parts(m1)
b = parts(m2)
c = parts(m3)
Here is what I need your help:
how to save m1, m2, m3 as a list which can persistent in a human readable database, next time only change that database itself I can add meta?
how to chain different parts as a new combination? Such as
e = a.linkwith(b)
d = c.linkwith(a)
and store it in that database as well?
can I make a long chain, make a new parts instance , such as
f = c.linkwith(a,b,d,e)
and findout easily which part is incapable to link in this chain, here part c with different size?
Many thanks.

I got bored. It's very rough but it works. If you take this far enough, you will want to use a database; but I understand wanting to use a human readable format.
from copy import copy
import csv
class Part_Base(object):
pass
class MultiPart_Base(list):
pass
class part_meta(type):
part_names = {}
parts = []
def __init__(cls, cls_name, cls_bases, cls_dict):
super(part_meta, cls).__init__(cls_name, cls_bases, cls_dict)
if(not Part_Base in cls_bases):
part_meta.part_names[cls_name] = cls
def __call__(self, *args, **kwargs):
name = kwargs.get("name", "")
if(part_meta.part_names.has_key(name) and not (self is part_meta.part_names[name])):
obj = part_meta.part_names[name].__call__(*args, **kwargs)
else:
obj = None
if(not part_meta.part_names.has_key(self.__name__)):
new_class = part_meta(name, (Generic_Part,), {})
globals()[name] = new_class
obj = new_class(*args, **kwargs)
else:
obj = super(part_meta, self).__call__(*args, **kwargs)
if not obj in part_meta.parts:
part_meta.parts.append(obj)
return obj
#classmethod
def save(cls):
all_fields = list(reduce(lambda x, y: x | set(y.fields), cls.parts, set([])))
with open("parts.csv", "w") as file_h:
writer = csv.DictWriter\
(
file_h,
all_fields,
restval = "",
extrasaction = "ignore",
dialect = "excel",
lineterminator = "\n",
)
writer.writeheader()
for part in cls.parts:
writer.writerow({field : getattr(part, field) for field in part.fields})
#classmethod
def load(cls):
with open("parts.csv", "r") as file_h:
reader = csv.DictReader(file_h)
for row in reader:
Part(**row)
class Part(Part_Base):
__metaclass__ = part_meta
fields = []
def __init__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
self.fields += kwargs.keys()
def __repr__(self):
return "<%s>" % self.description
#property
def description(self):
return "%s: %s %s %s %s" % (self.name, self.intype, self.outtype, self.shape, self.serialno)
def linkwith(self, *parts):
return Generic_MultiPart(self, *parts)
class Generic_Part(Part):
def __init__(self, **kwargs):
kwargs["name"] = self.__class__.__name__
super(Generic_Part, self).__init__(**kwargs)
class Generic_MultiPart(MultiPart_Base):
def __init__(self, *parts):
super(Generic_MultiPart, self).__init__()
if len(parts) >= 2:
self.shape = parts[0].shape
self.linkwith(*parts)
else:
raise ValueError("Not enough parts")
def __repr__(self):
return "<MultiPart: %s>" % super(Generic_MultiPart, self).__repr__()
def linkwith(self, *parts):
for part in parts:
if part.shape == self.shape:
if isinstance(part, Part):
self.append(part)
elif isinstance(part, MultiPart_Base):
self.extend(part)
else:
raise ValueError("Incompatible parts")
return self
class cooler(Generic_Part):
intype = "hotwater"
outtype = "coldwater"
fields = ["intype", "outtype"]
class heater(Generic_Part):
intype = "coldwater"
outtype = "hotwater"
fields = ["intype", "outtype"]
def make_some_parts():
some_parts = \
[
# This is actually a cooler object
# The metaclass uses the cooler class from above
# to create the object
Part
(
name = "cooler",
shape = "1/4 inch round",
serialno = "SN:11111"
),
# Using the heater class directly
heater
(
shape = "1/4 inch round",
serialno = "SN:22222"
),
Part
(
name = "purifier",
intype = "coldwater",
outtype = "hotwater",
shape = "1/6 inch round",
serialno = "SN:33333"
),
Part
(
name = "carbon_filter",
intype = "coldwater",
outtype = "coldwater",
shape = "1/4 inch round",
serialno = "SN:33333"
)
]
useless_part = some_parts[0].linkwith(some_parts[1])
print useless_part
filter_part = copy(useless_part).linkwith(some_parts[3])
print filter_part
part_meta.save()
def load_some_parts():
part_meta.load()
print part_meta.parts
You can manually edit parts.csv (in Excel or other) and it will make the parts described.
The save/restore functionality hasn't been extended to MultiParts; you can do that.

Related

Implementation of clone in QStandardItem subclass

I am using a QStandardItemModel with a QTreeView to display custom Items. The items come in three different types FILTER_TYPE, MODIFIER_TYPE and GROUP_TYPE.
I would like to be able to reorder items within the model using drag and drop in the view (InternalMove). If I understood it correctly, I have to use setItemPrototype(MyItem()) on my model in order for it to use the custom MyItem and not the general QStandardItem when moving items.
My understanding was that a new instance of the custom MyItem gets created and then all data and flags from the old item are copied over to the new item. However, it seems the model only initialises a new MyItem and never copies the data.
Therefore: How do I reimplement QStandardItem.clone() in the MyItem subclass to copy all data and flags into the new item? Do I have to manually go through all the custom data roles and assign their value to the new item?
The Item class looks like this:
class MyItem(QtGui.QStandardItem):
FILTER_TYPE = QtGui.QStandardItem.UserType + 1
MODIFIER_TYPE = QtGui.QStandardItem.UserType + 2
GROUP_TYPE = QtGui.QStandardItem.UserType + 3
TYPE = QtCore.Qt.UserRole + 0
NAME = QtCore.Qt.UserRole + 1
IS_PROCESSED = QtCore.Qt.UserRole + 5
OUTPUT = QtCore.Qt.UserRole + 6
FN = QtCore.Qt.UserRole + 7
DEFAULT_PARAMS = QtCore.Qt.UserRole + 8
PARAMETER_SET = QtCore.Qt.UserRole + 9
def __init__(self):
super().__init__()
self.name = ""
self.full_name = ""
self.description = ""
self.fn = None
self.default_params = None
self.parameter_set = None
self.is_active = True
self.is_processed = False
self.output = None
self.icon = QtGui.QIcon()
def clone(self):
item = Item()
??? WHAT GOES HERE TO COPY ALL DATA AND FLAGS ???
return item
def __setattr__(self, name, value):
if name == 'name':
self.setData(value, self.NAME)
elif name == 'full_name':
self.setData(value, QtCore.Qt.DisplayRole)
self.setData(value, QtCore.Qt.EditRole)
elif name == 'description':
self.setData(value, QtCore.Qt.ToolTipRole)
...
else:
super().__setattr__(name, value)
def __getattribute__(self, name):
if name == 'name':
return self.data(self.NAME)
elif name == 'full_name':
return self.data(QtCore.Qt.DisplayRole)
elif name == 'description':
return self.data(QtCore.Qt.ToolTipRole)
...
else:
return super().__getattribute__(name)
def initializeItem(self, type_, name, full_name, description="", fn=None, default_params=None):
self.name = name
self.full_name = full_name
self.description = description
self.fn = fn
self.default_params = default_params
self.parameter_set = ParameterSet(params_list=default_params)
self.setData(type_, self.TYPE)
flags = QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsDragEnabled|QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled
if type_ == self.FILTER_TYPE:
self.icon = QtGui.QIcon('resources/filter.png')
flags = flags|QtCore.Qt.ItemNeverHasChildren
elif type_ == self.MODIFIER_TYPE:
self.icon = QtGui.QIcon('resources/modifier.png')
flags = flags|QtCore.Qt.ItemIsDropEnabled
elif type_ == self.GROUP_TYPE:
self.icon = QtGui.QIcon('resources/folder.png')
flags = flags|QtCore.Qt.ItemIsDropEnabled|QtCore.Qt.ItemIsEditable
self.setFlags(flags)
def type(self):
return self.data(self.TYPE)
The Model implementation looks like this:
from tree.items import MyItem
class TreeModel(QtGui.QStandardItemModel):
def __init__(self):
super().__init__()
self.setItemPrototype(MyItem())
The logic of "clone" is to create an object with the same information of the item, so in this case you are using the roles to store that information so you must copy all that information in the new item, in this case you can use QDataStream:
def clone(self):
item = MyItem()
ba = QtCore.QByteArray()
ds = QtCore.QDataStream(ba, QtCore.QIODevice.WriteOnly)
ds << self
ds = QtCore.QDataStream(ba)
ds >> item
return item

Convert node tree to dictionary

Below is the node class definition with tree structure (built using node instance) of programming languages. Now how to convert hierarchical node data tree structure to python dictionary using node class method ?
See desired output at bottom.
class Node(object):
def __init__(self, name, parent=None):
self._name = name
self._children = []
self._parent = parent
if parent is not None:
parent.addChild(self)
def addChild(self, child):
self._children.append(child)
def name(self):
return self._name
def setName(self, name):
self._name = name
def child(self, row):
return self._children[row]
def childCount(self):
return len(self._children)
def parent(self):
return self._parent
rootNode = nodeData.Node("books")
web_node = nodeData.Node("web", rootNode)
database_node = nodeData.Node("database", rootNode)
front_end_node = nodeData.Node("front-end", web_node)
back_end_node = nodeData.Node("back-end", web_node)
sql_node = nodeData.Node("sql", database_node)
nosql_node = nodeData.Node("nosql", database_node)
html_node = nodeData.Node("html", front_end_node)
css_node = nodeData.Node("css", front_end_node)
js_node = nodeData.Node("js", front_end_node)
php_node = nodeData.Node("php", back_end_node)
python_node = nodeData.Node("python", back_end_node)
mysql_node = nodeData.Node("mysql", sql_node)
postgresql_node = nodeData.Node("postgresql", sql_node)
mongodb_node = nodeData.Node("mongodb", nosql_node)
cassandra_node = nodeData.Node("cassandra", nosql_node)
html_book_one_node = nodeData.Node("the missing manual", html_node)
html_book_two_node = nodeData.Node("core html5 canvas", html_node)
css_book_one_node = nodeData.Node("css pocket reference", css_node)
css_book_two_node = nodeData.Node("css in depth", css_node)
js_book_one_node = nodeData.Node("you don't know js", js_node)
js_book_two_node = nodeData.Node("eloquent javascript", js_node)
php_book_one_node = nodeData.Node("modern php", php_node)
python_book_one_node = nodeData.Node("dive into python", python_node)
python_book_two_node = nodeData.Node("python for everybody", python_node)
python_book_three_node = nodeData.Node("Think Python", python_node)
mongodb_book_one_node = nodeData.Node("mongodb in action", mongodb_node)
mongodb_two_node = nodeData.Node("scaling mongodb", mongodb_node)
Output
From node tree abstraction to python dictionary
{"books":{
"web":{
"front-end":{
"html":["the missing manual", "core html5 canvas"],
"css":["css pocket reference", "css in depth"],
"js":["you don't know js", "eloquent javascript"]
},
"back-end":{
"php":["modern php"],
"python":["dive into python", "python for everybody",
"Think Python"]
}
},
"database":{
"sql":{
"mysql":[],
"postgresql":[]
},
"nosql":{
"mongodb":["mongodb in action", "scaling mongodb"],
"cassandra":[]
}}}}
Updated Code
class Node(object):
def __init__(self, name, parent=None):
self._name = name
self._children = []
self._parent = parent
if parent is not None:
parent.addChild(self)
def addChild(self, child):
self._children.append(child)
def name(self):
return self._name
def setName(self, name):
self._name = name
def child(self, row):
return self._children[row]
def childCount(self):
return len(self._children)
def parent(self):
return self._parent
class categoryNode(Node):
def __init__(self, name, parent=None):
super(categoryNode, self).__init__(name, parent)
class subCategoryNode(Node):
def __init__(self, name, parent=None):
super(subCategoryNode, self).__init__(name, parent)
class languageNode(Node):
def __init__(self, name, parent=None):
super(languageNode, self).__init__(name, parent)
class BookNode(Node):
def __init__(self, name, parent=None):
super(BookNode, self).__init__(name, parent)
rootNode = Node("books")
web_node = categoryNode("web", rootNode)
database_node = categoryNode("database", rootNode)
front_end_node = subCategoryNode("front-end", web_node)
back_end_node = subCategoryNode("back-end", web_node)
sql_node = subCategoryNode("sql", database_node)
nosql_node = subCategoryNode("nosql", database_node)
html_node = languageNode("html", front_end_node)
css_node = languageNode("css", front_end_node)
js_node = languageNode("js", front_end_node)
php_node = languageNode("php", back_end_node)
python_node = languageNode("python", back_end_node)
mysql_node = languageNode("mysql", sql_node)
postgresql_node = languageNode("postgresql", sql_node)
mongodb_node = languageNode("mongodb", nosql_node)
cassandra_node = languageNode("cassandra", nosql_node)
html_book_one_node = BookNode("the missing manual", html_node)
html_book_two_node = BookNode("core html5 canvas", html_node)
css_book_one_node = BookNode("css pocket reference", css_node)
css_book_two_node = BookNode("css in depth", css_node)
js_book_one_node = BookNode("you don't know js", js_node)
js_book_two_node = BookNode("eloquent javascript", js_node)
php_book_one_node = BookNode("modern php", php_node)
python_book_one_node = BookNode("dive into python", python_node)
python_book_two_node = BookNode("python for everybody", python_node)
python_book_three_node = BookNode("Think Python", python_node)
mongodb_book_one_node = BookNode("mongodb in action", mongodb_node)
mongodb_two_node = BookNode("scaling mongodb", mongodb_node)
You have a bigger problem, because you're using the same class to represent both book categories and actual books. Given this, it is impossible to programmatically determine that mysql_node and postgresql_node are empty categories rather than books.
To make this work how you want, you will need to redesign the data structure. I suggest having a list _children for subcategories and another list _books for book titles (as strings). Note that this data structure is still a little ambiguous because a node with no subcategories and no books could be rendered as an empty list (i.e. a terminal category with no books) or an empty dictionary (i.e. a non-terminal category with no subcategories); I infer from the question that an empty list is the desired result.
class Node:
def __init__(self, name, parent=None):
self._name = name
self._children = []
self._parent = parent
self._books = []
if parent is not None:
parent.addChild(self)
def name(self):
return self._name
def setName(self, name):
self._name = name
def parent(self):
return self._parent
def addChild(self, child):
if self._books:
raise ValueError('Node cannot have both sub-categories and books')
self._children.append(child)
def child(self, row):
return self._children[row]
def childCount(self):
return len(self._children)
def addBook(self, book):
if self._children:
raise ValueError('Node cannot have both sub-categories and books')
self._books.append(book)
def book(self, row):
return self._books[row]
def bookCount(self):
return len(self._books)
rootNode = Node("books")
web_node = Node("web", rootNode)
database_node = Node("database", rootNode)
front_end_node = Node("front-end", web_node)
back_end_node = Node("back-end", web_node)
sql_node = Node("sql", database_node)
nosql_node = Node("nosql", database_node)
html_node = Node("html", front_end_node)
css_node = Node("css", front_end_node)
js_node = Node("js", front_end_node)
php_node = Node("php", back_end_node)
python_node = Node("python", back_end_node)
mysql_node = Node("mysql", sql_node)
postgresql_node = Node("postgresql", sql_node)
mongodb_node = Node("mongodb", nosql_node)
cassandra_node = Node("cassandra", nosql_node)
html_node.addBook("the missing manual")
html_node.addBook("core html5 canvas")
css_node.addBook("css pocket reference")
css_node.addBook("css in depth")
js_node.addBook("you don't know js")
js_node.addBook("eloquent javascript")
php_node.addBook("modern php")
python_node.addBook("dive into python")
python_node.addBook("python for everybody")
python_node.addBook("Think Python")
mongodb_node.addBook("mongodb in action")
mongodb_node.addBook("scaling mongodb")
def node_to_dict(node):
def helper(n):
if n.childCount() > 0:
return { c.name(): helper(c) for c in n._children }
else:
return list(n._books)
return { node.name(): helper(node) }
The result of node_to_dict(rootNode) does == your expected output.
Simple recursive function:
def to_dict(node):
if isinstance(node, nodeData.Node):
return {node._name:to_dict(node._children)}
if all(isinstance(i, nodeData.Node) for i in node):
return (lambda x:x if all(x.values()) else list(x))({i._name:to_dict(i._children) for i in node})
return node
print(to_dict(rootNode))
Output:
{'books': {'web': {'front-end': {'html': ['the missing manual', 'core html5 canvas'], 'css': ['css pocket reference', 'css in depth'], 'js': ["you don't know js", 'eloquent javascript']}, 'back-end': {'php': ['modern php'], 'python': ['dive into python', 'python for everybody', 'Think Python']}}, 'database': {'sql': ['mysql', 'postgresql'], 'nosql': ['mongodb', 'cassandra']}}}

Making the file_names unique with timestamp in django image upoads

Intro: I have a small piece of code that takes any image that is being added and makes it smaller and saves it. I am using a external library called Filepond for this.
The Issue: If 2 users add same names to their images(different images). The second users image replaces the 1st users image and both users see the same image.
What I want: Add unique image names. My tries are below the present code. I need the best solution for this so the names are not too big but are unique
Present Code:
fields.py:
class FilePondField(forms.FileField):
widget = forms.TextInput(attrs={'class': 'fileid'})
def __init__(self, name, *args, **kwargs):
super(FilePondField, self).__init__(*args, **kwargs)
self.name = name
def prepare_value(self, data):
if not data:
return None
if isinstance(data, str):
try:
tu = TU.objects.get(upload_id=data)
except TU.DoesNotExist:
return None
return tu.upload_id
name = data.name
base = os.path.basename(name)
file_id = "%s_%s" % (self.name, data.instance.pk)
try:
tu = TU.objects.get(file_id=file_id)
except TU.DoesNotExist:
upload_id = uuid()
tu = TU(upload_id=upload_id, file_id=file_id, # uuid(),
upload_name=base, upload_type=TU.FILE_DATA)
try:
with data.storage.open(name, 'rb') as f:
rd_data = File(f)
tu.file.save(tu.file_id, rd_data, True)
tu.save()
except:
pass
return tu.upload_id
def clean(self, data, initial=None):
self.initial = initial
if not data:
if self.required:
raise ValidationError(self.error_messages['required'], code='required')
return None
return data
def save_cb(self, instance, modfld, tu):
prename = os.path.join(modfld.upload_to, tu.upload_name)
ffile = ImageFieldFile(instance, modfld, prename)
try:
with open(tu.get_file_path(), 'rb') as f:
data = File(f)
ffile.save(tu.upload_name, data, False)
except:
pass
return ffile
def do_tmp(self, instance, modfld, value, cb):
try:
tu = TU.objects.get(upload_id=value)
ffile = cb(instance, modfld, tu) if cb else None
except TU.DoesNotExist:
ffile = None
else:
tu.delete()
file_id = "%s_%s" % (self.name, instance.pk)
try:
ogtu = TU.objects.get(file_id=file_id)
except TU.DoesNotExist:
pass
else:
ogtu.delete()
return ffile
def save(self, instance, modfld, value):
return self.do_tmp(instance, modfld, value, self.save_cb)
def del_tmp(self, instance, modfld, value):
self.do_tmp(instance, modfld, value, None)
def bound_data(self, data, initial):
return data
def has_changed(self, initial, data):
if not initial:
return data
return initial != data
forms.py
class ImageForm(forms.ModelForm):
img_fields = []
def __init__(self, *args, **kwargs):
super(ImageForm, self).__init__(*args, **kwargs)
for (fld, fargs) in self.img_fields:
self.fields[fld] = FilePondField(fld, **fargs)
def save(self, *args, **kwargs):
commit = kwargs.get('commit', True)
for (fld_nm, fargs) in self.img_fields:
fld = dict([(f.name, f) for f in self._meta.model._meta.fields])[fld_nm]
if isinstance(self.fields[fld_nm], FilePondField):
self.fields[fld_nm] = self.fields[fld_nm].save(self.instance, fld, self.cleaned_data[fld_nm])
return super(ImageForm, self).save(*args, **kwargs)
def del_tmp (self):
for (fld_nm, fargs) in self.img_fields:
fld = dict([(f.name, f) for f in self._meta.model._meta.fields])[fld_nm]
if isinstance(self.fields[fld_nm], FilePondField):
self.fields[fld_nm].del_tmp(self.instance, fld, self.cleaned_data[fld_nm])
My Approach:
in fields.py I import
In the function def prepare_value(self, data): and def do_tmp(self, instance, modfld, value, cb): I make the below changes
...
file_id = "%s_%s_%s" % (self.name, data.instance.pk, datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f"))
...
Can someone comment on this or suggest a better alternative
Just use datetime.now() value for the file name such as below:
from datetime import datetime
open(str(datetime.now()) + ".txt", "w+")
Result: It creates a file named 2019-04-22 00:21:31.862001.txt
make the name a variable like this
name = "Your-General-Name-{}".format((int(time.time())))
and then put it in your loop so that the time.time() value changes each time. You obviously dont have to use time.time(). you could use datetime.datetime.now() etc. but then you'd just replace the time function.

Python Dict w/Array Values Passed as Params?

Alright so I have a dict with keys that point to an array of 5 values. These 5 values I pass to a class to sort out and feed me info etc.
Main
So, this works, but my querstion is is there a better way of exytracting the array to pass to the 'weapon' class, or do i just need to 'wepstats[0],wepstats[1]' etc? Or is there a better way of going about this? I'm all ears as Im only learning to do this stuff.
class Main():
def weaponDamage(self):
#print 15 * 2.22
wdb = WeaponDB()
wepstats = wdb.getWeaponStats('Sword')
wep = Weapon(wepstats[0],wepstats[1],wepstats[2],wepstats[3],wepstats[4])
wep2 = Weapon("Sword", 5, 55, 1.55, 2.1)
print wep
print wep2
s = sayThings()
greet = s.Say()
self.crit = wep.getDamageCrtRND()
self.scrit = wep.getDamageSCrtRND()
self.avg = wep.getDamageAvg()
self.high = wep.getDamageHigh()
self.low = wep.getDamageLow()
self.mod = wep.getDamageMod()
self.norm = wep.getDamageNrmRND()
self.name = wep.getWeaponName()
print greet
print "-----------"
print "Name: " + self.name
print "-----------"
print "High: %s" % self.high
print "Low : %s" % self.low
print "Avg : %s" % self.avg
print "Crit: %s" % self.crit
print "--------------------"
Dict
EDIT: Should I be making a DB of items in this manner in the first place? Is there a more logic method of doing this?
class WeaponDB():
"""Here be thine weapons of thy holy might"""
def __init__(self):
self.script = {
'None': "Error: No Weapon stats to get selected.",
'Sword': ("Sword", 5, 55, 1.55, 2.1),
}
def getWeaponStats(self, key = 'None'):
try:
return self.script[key]
except KeyError:
return self.script['None']
Class useing the values as parameters
class Weapon():
def __init__(self, name = "Stick", high = 1, low = 0, critMod = 1, scritMod = 2):
self.rng = randNum()
self.name = name
self.high = high
self.low = low
self.critMod = critMod
self.scritMod = scritMod
def getWeaponName(self):
return self.name
def getDamageHigh(self):
return self.high
def getDamageLow(self):
return self.low
def getDamageMod(self):
return self.critMod
def getDamageSMod(self):
return self.scritMod
etc...
If I understand well you can do something like this:
class Weapon:
def __init__( self, name = 'Stick', high = 1, low = 0 ):
self.name = name
self.high = high
self.low = low
wepstats = ( 'Sword', 5, 55 )
sword = Weapon( *wepstats )
Then if you check your attributes you get:
>>> sword.name
'Sword'
>>> sword.high
5
>>> sword.low
55
Using *wepstats you pass the entire tuple as arguments for your constructor.

printing objects in python

I'm trying to print these car_object[objectname] objects, but not sure how to do it....
I also have a Cars class. When I do print(car_object[objectname]) I get ObjectmeA160
<__main__.Cars object at 0x027FB970>. what am I doing wrong?
def __iter__(self):
car_object = {}
cursor = self._db.execute('SELECT IDENT, MAKE, MODEL, DISPLACEMENT,
POWER, LUXURY FROM CARS')
for row in cursor:
car_object = {}
objectname = 'Object'+str(row['IDENT'])
car_object[objectname] = Cars(ident = row['IDENT'], make = row['MAKE'],
model = row['MODEL'], disp = row['DISPLACEMENT'], power = row['POWER'], luxury = row['LUXURY'])
print(car_object[objectname])
yield dict(row)
class Cars:
def __init__(self, **kwargs):
self.variables = kwargs
def set_Variable(self, k, v):
self.variables[k] = v
def get_Variable(self, k):
return self.variables.get(k, None)
The <__main__.Cars object at 0x027FB970> is the standard string for custom objects that do not implement their own .__str__() hook. You can customize it by implementing that method:
class Cars:
# ....
def __str__(self):
return 'Car instance with variables: {!r}'.format(self.variables)

Categories

Resources