Pyhon进阶9---类的继承
类的继承
基本概念
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。定义
格式如下
继承中的访问控制
class Animal: __CNOUT = 0 HEIGHT = 0 def __init__(self,age,weight,height): self.__CNOUT += 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) @classmethod def showcount1(cls): print(cls.__CNOUT) @classmethod def __showcount2(cls): print(cls.__CNOUT) class Cat(Animal): NAME = 'CAT' c = Cat(3,5,15) c.eat() c.showcount1()#注意此处的cls.__COUNT仍为0 print(c.NAME) print(c.__dict__)#{'_Animal__CNOUT': 1, 'age': 3, '_Animal__weight': 5, 'HEIGHT': 15} print(Cat.__dict__)#{'__module__': '__main__', 'NAME': 'CAT', '__doc__': None} print(Animal.__dict__)
方法的重写、覆盖override
class Animal: def shout(self): print('Animal shout') class Cat(Animal): #覆盖父类的方法 def shout(self): print('miao') #覆盖自身的方法,显示调用了父类的方法 def shout(self): print(super(Cat, self)) print(super(Cat,self)) super().shout() a = Animal() a.shout() c =Cat() c.shout() #输出结果: # Animal shout # <super: <class 'Cat'>, <Cat object>> # <super: <class 'Cat'>, <Cat object>> # Animal shout
class Animal: @classmethod def class_method(cls): print('class_method_animal') @staticmethod def static_method(): print('static_method_animal') class Cat(Animal): @classmethod def class_method(cls): print('class_method_cat') @staticmethod def static_method(): print('static_method_cat') c = Cat() c.class_method() c.static_method() #输出结果: # class_method_cat # static_method_cat
继承中的初始化
示例1
class A: def __init__(self): self.a1 = 'a1' self.__a2 = 's2' print('A init') class B(A): pass b = B() print(b.__dict__) #{'a1': 'a1', '_A__a2': 's2'}
示例2
class A: def __init__(self): self.a1 = 'a1' self.__a2 = 's2' print('A init') class B(A): def __init__(self): self.b1 = 'b1' print('B init') b = B() print(b.__dict__) #{'b1': 'b1'}
class A: def __init__(self): self.a1 = 'a1' self.__a2 = 's2' print('A init') class B(A): def __init__(self): # A.__init__(self) # super(B,self).__init__() super().__init__() self.b1 = 'b1' print('B init') b = B() print(b.__dict__) #{'a1': 'a1', '_A__a2': 's2', 'b1': 'b1'}
如何正确初始化
class Animal: def __init__(self,age): print('Animal init') self.age =age def show(self): print(self.age) class Cat(Animal): def __init__(self,age,weight): super().__init__(age)#c.show()结果为11 print('Cat init') self.age = age + 1 self.weight = weight # super().__init__(age)#c.show()结果为10 c = Cat(10,5) c.show()
class Animal: def __init__(self,age): print('Animal init') self.__age =age def show(self): print(self.__age) class Cat(Animal): def __init__(self,age,weight): super().__init__(age) print('Cat init') self.__age = age + 1 self.__weight = weight c = Cat(10,5) c.show() print(c.__dict__)#{'_Animal__age': 10, '_Cat__age': 11, '_Cat__weight': 5}
Python不同版本的类
多继承
多继承弊端
Python多继承实现
class ClassName(基类列表): 类体

更多精彩