What is the difference between class and instance attributes?

后端 未结 5 1580
面向向阳花
面向向阳花 2020-11-21 05:44

Is there any meaningful distinction between:

class A(object):
    foo = 5   # some default value

vs.

class B(object):
    d         


        
5条回答
  •  感动是毒
    2020-11-21 06:13

    There is one more situation.

    Class and instance attributes is Descriptor.

    # -*- encoding: utf-8 -*-
    
    
    class RevealAccess(object):
        def __init__(self, initval=None, name='var'):
            self.val = initval
            self.name = name
    
        def __get__(self, obj, objtype):
            return self.val
    
    
    class Base(object):
        attr_1 = RevealAccess(10, 'var "x"')
    
        def __init__(self):
            self.attr_2 = RevealAccess(10, 'var "x"')
    
    
    def main():
        b = Base()
        print("Access to class attribute, return: ", Base.attr_1)
        print("Access to instance attribute, return: ", b.attr_2)
    
    if __name__ == '__main__':
        main()
    

    Above will output:

    ('Access to class attribute, return: ', 10)
    ('Access to instance attribute, return: ', <__main__.RevealAccess object at 0x10184eb50>)
    

    The same type of instance access through class or instance return different result!

    And i found in c.PyObject_GenericGetAttr definition,and a great post.

    Explain

    If the attribute is found in the dictionary of the classes which make up. the objects MRO, then check to see if the attribute being looked up points to a Data Descriptor (which is nothing more that a class implementing both the __get__ and the __set__ methods). If it does, resolve the attribute lookup by calling the __get__ method of the Data Descriptor (lines 28–33).

提交回复
热议问题