What is the python attribute get and set order?

后端 未结 2 532
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-17 00:27

Python provides us many possibilities on instance/class attribute, for example:

class A(object):
    def __init__(self):
        self.foo = \"hello\"

a = A(         


        
2条回答
  •  忘掉有多难
    2020-12-17 00:57

    I found out this great post that has a detailed explanation on object/class attribute lookup.

    For object attribute lookup:

    Assuming Class is the class and instance is an instance of Class, evaluating instance.foobar roughly equates to this:

    • Call the type slot for Class.__getattribute__ (tp_getattro). The default does this:
      • Does Class.__dict__ have a foobar item that is a data descriptor ?
        • If yes, return the result of Class.__dict__['foobar'].__get__(instance, Class).
      • Does instance.__dict__ have a 'foobar' item in it?
        • If yes, return instance.__dict__['foobar'].
      • Does Class.__dict__ have a foobar item that is not a data descriptor [9]?
        • If yes, return the result of Class.__dict__['foobar'].__get__(instance, klass). [6]
    • If the attribute still wasn't found, and there's a Class.__getattr__, call Class.__getattr__('foobar').

    There is an illustrated image for this:

    Please do check out the original blog if interested which gives a outstanding explanation on python class, attribute lookup, and metaclass.

提交回复
热议问题