Tuesday, December 13, 2011

when is a no-op not a no-op?

When is a = a not a no-op?  When a is a class variable accessed through self.a.  May be useful when you want a dynamic initializer for your instances on your class.  For example, a property like time_created.

>>> class A(object):
...    w = 4
...    def __init__(self):
...       self.w = self.w
...
>>> A()
<__main__.A object at 0x00DAE770>
>>> A().__dict__
{'w': 4}
>>> a = A()
>>> a.__dict__
{'w': 4}
>>> a.w = 5
>>> A.w
4
>>> a.w
5

No comments:

Post a Comment