what's the biggest difference between dir and __dict__ in python

前端 未结 2 1888
旧时难觅i
旧时难觅i 2020-11-28 02:00
class C(object):
    def f(self):
        print self.__dict__
        print dir(self)
c = C()
c.f()

output:

{}

[\'__class__\', \'_         


        
2条回答
  •  悲&欢浪女
    2020-11-28 02:29

    The function f belongs to the dictionary of class C. c.__dict__ yields attributes specific to the instance c.

    >>> class C(object):
        def f(self):
            print self.__dict__
    
    
    >>> c = C()
    >>> c.__dict__
    {}
    >>> c.a = 1
    >>> c.__dict__
    {'a': 1}
    

    C.__dict__ would yield attributes of class C, including function f.

    >>> C.__dict__
    dict_proxy({'__dict__': , '__module__': '__main__', '__weakref__': , '__doc__': None, 'f': })
    

    While an object can refer to an attribute of its class (and indeed all the ancestor classes), the class attribute so referred does not become part of the associated dict itself. Thus while it is legitimate access to function f defined in class C as c.f(), it does not appear as an attribute of c in c.__dict__.

    >>> c.a = 1
    >>> c.__dict__
    {'a': 1}
    

提交回复
热议问题