Skip to content

Instantly share code, notes, and snippets.

@MOON-CLJ
Last active December 19, 2015 22:29
Show Gist options
  • Save MOON-CLJ/6028017 to your computer and use it in GitHub Desktop.
Save MOON-CLJ/6028017 to your computer and use it in GitHub Desktop.
python Lookup instance attribute
In [88]: class C:
....: def foo(self):
....: pass
....: foo = classmethod(foo)
....:
In [89]: C.__dict__
Out[89]:
{'__doc__': None,
'__module__': '__main__',
'foo': <classmethod at 0x102fbd868>}
In [90]: C.foo
Out[90]: <bound method classobj.foo of <class __main__.C at 0x102fd0050>>
In [91]: class C:
....: def foo(self):
....: pass
....:
In [94]: C.__dict__
Out[94]: {'__doc__': None, '__module__': '__main__', 'foo': <function __main__.foo>}
In [95]: C.foo
Out[95]: <unbound method C.foo>
non-data descriptor能够被同名attribute覆盖 而data descriptor不能
If attrname is a special (i.e. Python-provided) attribute for objectname, return it.
Check objectname.__class__.__dict__ for attrname. If it exists and is a data-descriptor, return the descriptor result. Search all bases of objectname.__class__ for the same case.
Check objectname.__dict__ for attrname, and return if found. If objectname is a class, search its bases too. If it is a class and a descriptor exists in it or its bases, return the descriptor result.
Check objectname.__class__.__dict__ for attrname. If it exists and is a non-data descriptor, return the descriptor result. If it exists, and is not a descriptor, just return it. If it exists and is a data descriptor, we shouldn't be here because we would have returned at point 2. Search all bases of objectname.__class__ for same case.
Raise AttributeError
http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html
http://python-history.blogspot.jp/2010/06/inside-story-on-new-style-classes.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment