[python]父类、子类、子类实例属性

发布时间:2019-03-16 22:44:23编辑:auto阅读(1892)

     

    本文旨在说明 父类、子类、子类实例的属性继承关系:

     

     

    >>> A = type('A', (), {'name':1})
    >>> B = type('B',(A,), {'addr':'beijing'})    #B的父类为A
    >>> A.__dict__
    mappingproxy({'name': 1, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})
    >>> B.__dict__
    mappingproxy({'addr': 'beijing', '__module__': '__main__', '__doc__': None})
    >>> b = B()
    >>> b.__dict__
    {}            #__dict__查看每个对象自身的属性,无法暴露继承的属性
    >>> dir(b)        #dir()可以查看所有有效属性
    ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'addr', 'name']
    >>> b.addr, b.name      #以下代码验证了:上游对象更改属性的值,下游皆会继承该值;若下游对象给属性重新赋值了,那么上游再改变属性值时对下游无影响;
    ('beijing', 1)
    >>> A.name = 999
    >>> b.name, B.name
    (999, 999)
    >>> A.name = 0
    >>> b.name, B.name
    (0, 0)
    >>> B.name = 888
    >>> A.name, b.name
    (0, 888)
    >>> A.name = 777
    >>> B.name, b.name
    (888, 888)
    >>> b.name = 666
    >>> A.name, B.name, b.name
    (777, 888, 666)
    >>> B.name = 555
    >>> b.name
    666

     

关键字