home Glamenv-Septzen(ぐらめぬ・ぜぷつぇん)(archive)

Python/codepiece/特殊メソッド/1.属性参照の__setattr__,__getattr__

作成日: 2009-03-21 23:03:31   /   last updated at: 2009-03-21 23:21:52
カテゴリ: Python 

属性参照、およびメモリ節約の為の__slots__属性については例によりEffectivePythonが分かりやすくまとまっている。

Python Document (2.5) でも、Language Referenceに "3.4.2 Customizing attribute access" として説明がある。

t_specialattrs_attr.py :

class C(object):

  def __getattr__(self, name):
    print "__getattr__(self, " + name + ")"
    if name in self.__dict__:
      #return self.__dict__[name] # 新形式でない場合はこちら。
      return object.__getattr__(self, name) # 新形式ならこっち。
    else:
      print 'no key:', name
      return None

  def __setattr__(self, name, value):
    print "__setattr__(self, " + name + ", " + repr(value) + ")"
    #self.__dict__[name] = value # 新形式でない場合はこちら。
    object.__setattr__(self, name, value) # 新形式ならこっち。

  def __delattr__(self, name):
    print "__delattr__(self, " + name + ")"
    #del self.__dict__[name] # 新形式でない場合はこちら。
    object.__delattr__(self, name) # 新形式ならこっち。

c = C()
c.v1 = 'abc'
print c.v1
print c.v2
print repr(c.__dict__)
del c.v1
print repr(c.__dict__)
> python t_specialattrs_attr.py
__setattr__(self, v1, 'abc')  ... c.v1 = 'abc'
abc                           ... print c.v1
__getattr__(self, v2)         ... print c.v2
no key: v2
None
{'v1': 'abc'}                 ... print repr(c.__dict__)
__delattr__(self, v1)         ... del c.v1
{}                            ... print repr(c.__dict__)

original url: https://www.glamenv-septzen.net/view/221