[Tutor] Descriptors and type declaration order
Emile van Sebille
emile at fenx.com
Thu Jul 14 14:22:07 CEST 2011
On 7/14/2011 2:44 AM Knacktus said...
> Hi guys,
>
> I've got the following (not working) code:
>
> class Attribute(object):
>
> def __init__(self, attribute_name, att_type_name):
> self._attribute_name = attribute_name
> try:
> self._attribute_type = globals()[att_type_name]
> except KeyError:
> self._attribute_type = getattr(globals()["__builtins__"],
> att_type_name)
>
> def __get__(self, obj, obj_type):
> return getattr(obj, self._attribute_name)
>
> def __set__(self, obj, value):
> if isinstance(value, self._attribute_type):
> setattr(obj, self._attribute_name, value)
> else:
> raise ItemTypeException(self._attribute_type, type(value))
>
> class BaseItem(object):
>
> ident = Attribute("ident", "int")
> owner = Attribute("owner", "str")
> item = Attribute("item", "BaseItem")
>
> if __name__ == "__main__":
> print "About to create an item"
> test = BaseItem()
> print "OK"
>
> The problem is that the descriptors are created when the module is
> evaluated. But at this time the class BaseItem is not known yet. Any ideas?
You want to embed an instance of a class as an attribute of the same
class? Does this help:
class BaseItem(object):
ident = Attribute("ident", "int")
owner = Attribute("owner", "str")
BaseItem.item = Attribute("item", "BaseItem")
Emile
More information about the Tutor
mailing list