python - if a property sample work -
in book of "core python programming", there sample how use property. code this:
class hidex(object): def __init__(self, x): self.__x = x @property def x(): def fget(self): return ~self.__x def fset(self, x): assert isinstance(val, int), 'val must int' self.__x = ~x return locals()
the book says, class work following code:
inst = hidex(20) print inst.x inst.x = 30 print inst.x
but don't think class work. because when access inst.x, interpreter run hidex.__dict__['x'].__get__(x, hidex)
, , because x = property(x), first arg 'fget' of property x, rather function 'fget' defined in x().
also, when run code, got result of:
{'fget': <function fset @ 0x.....>, 'self': <__main__.xxxx>, 'fget': <function fget @ 0x....>} traceback: ...... # result telling t.x = 30 cannot run, skip details attributeerror: cannot set attribute
do miss something? why book intend can work?
this make sence:
class hidex(object): def __init__(self, x): self.__x = x @property def x(self): return ~self.__x @x.setter def x(self, x): assert isinstance(x, int), 'val must int' self.__x = ~x
looks @property
in code of question not builtin different version.
this intended here:
def nested_property(func): """make defining properties simpler. """ names = func() names['doc'] = func.__doc__ return property(**names) class hidex(object): def __init__(self, x): self.__x = x @nested_property def x(): def fget(self): return ~self.__x def fset(self, x): assert isinstance(x, int), 'val must int' self.__x = ~x return locals()
Comments
Post a Comment