Reputation: 33
i would like to add to attributes of an object in Python some information. Later i would like to store this data in a DB, therefore it would be neat to know its format in the tables. I think the solution from SQLAlchemy is good and i would like to do it like that.
First a short example:
class MyAttribute(object):
def __init__(self, AttrType):
self.val = None
self.AttrType = AttrType
def __get__(self, obj, objtype):
return self.val
def __set__(self, obj, val):
self.val = val
class MyClass(object):
Attr1 = MyAttribute('int(11)')
def __init__(self):
self.Attr1 = 44
self.Attr2 = 55
x = MyClass()
print("Attr1: %s"%x.Attr1)
print("Attr2: %s"%x.Attr2)
print(x.__dict__)
The output of this script is:
Attr1: 44
Attr2: 55
{'Attr2': 55}
Now my problem: in __dict__
, there is Attr2
, but not Attr1
. Why? How can I add it? Which function is responsible for that? (My read is __set__
, correct?) What do I have to add where to add the attribute object to the dict?
Upvotes: 2
Views: 746
Reputation: 97681
Try MyClass.__dict__
:
>>> MyClass.__dict__['Attr1']
<__main__.MyAttribute object at 0x000000000296A5F8>
Descriptors are stored in the class object, not the instance object. You're actually in trouble here, for that reason:
>>> x = MyClass()
>>> x.Attr1
44
>>> y = MyClass()
>>> y.Attr1 = 66
>>> y.Attr1
66
>>> x.Attr1
66 # uh oh
It's the job of MyAttribute to keep track of which data belongs to which instance.
Upvotes: 1