python 继承 inherit

  

class Animal:
    x=123
    def __init__(self,name):
        self._name=name
        self.__age=10
    @property
    def name(self):
        return self._name
    def shout(self):
        print('Animal shout')

class Cat(Animal):
    x='cat'
    def __init__(self,name):
        Animal.__init__(self,name)
        self._name='CAT'+name
        self.__age=20

    def shout(self): # override
        print('miao')
        Animal.__init__(self,'abc')
class Garfield(Cat):
    pass
class PersiaCat(Cat):
    # def __init__(self):
    #     self.eyes='blue'
    pass

class Dog(Animal):
    def run(self):
        print("Dog Run")

tom=Garfield('tom')
print(tom.__dict__) # overload self._name 继承了改名后的Animal和Cat的私有属性__age,但是不能直接访问
print(tom.name) # Animal的property属性,self对象寻找,object->subclass->baseclass
print(tom._name)
print(tom.shout()) # 调用了Animal的__init__方法,进行了属性重定义,Animal中的__init__方法中self.__age=10 => self._Animal__age=10
print(tom._name)
print(tom.__dict__)
print(Cat.__dict__)
print(Animal.__dict__)

  

 

class Animal:
    __COUNT=0
    HEIGHT=0
    NAME='uiop'
    def __init__(self,age,weight,height):
        self.__COUNT+=1
        self.age=age
        self.__weight=weight
        self.HEIGHT=height

    def eat(self):
        print('{} eat'.format(self.__class__.__name__))

    def __getweight(self):
        print(self.__weight)

    def getname(self):
        return self.NAME
    @classmethod
    def showcount1(cls):
        print(cls.__COUNT)

    @classmethod
    def __showcount2(cls):
        print(cls.__COUNT)

class Cat(Animal):
    NAME='cat class'
    __COUNT='zxc'
    # def getweight(self): getweight 获取不到对象的_Cat__weight属性,因为父类做了隐藏替换
    #     return self.__weight

c=Cat(3,5,15)
c.eat()
print(c.HEIGHT)
print(Animal.__dict__)
c.showcount1() # 此 classmethod传递的cls为Cat,但是Animal中showcount1的__COUNT已经
被替换成_Animal__COUNT(私有属性),所以取值为Animal中的__COUNT,不会取Cat的__COUNT print(c._Cat__COUNT) print(c.getname()) # object寻找时,虽然为父类的方法,但是传递的对象为Cat object,寻找顺序为子类
->父类,区别于classmethod # print('{}'.format(Animal.__dict__)) # print('{}'.format(Cat.__dict__)) # print(c.__dict__) # print(c.getweight()) print(c.__class__.mro()) print(c.__class__.__mro__) # method resolution order print(Cat.__bases__) # 类的基类列表 print(Cat.__base__) # 类的基类 print(Cat.__subclasses__()) print(Animal.__subclasses__()) # 类的子类列表 print(Animal.__dict__)

 

posted @ 2020-10-03 13:14  ascertain  阅读(252)  评论(0编辑  收藏  举报