零基础小白入门必看篇:学习Python之面对对象基础( 四 )

# 如果是先调用了父类的属性和方法,父类属性会覆盖子类属性,故在调用属性前,先调用自己子类的初始化 self.__init__() print(f'运用{self.kongfu}制作煎饼果子') # 调用父类方法, 但是为保证调用到的也是父类的属性,必须在调用方法前调用父类的初始化 def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) daqiu = Prentice() daqiu.make_cake() daqiu.make_master_cake() daqiu.make_school_cake() daqiu.make_cake()

  • 多层继承class Master(object): def __init__(self): self.kongfu = '[古法煎饼果?配?]' def make_cake(self): print(f'运?{self.kongfu}制作煎饼果?') class School(object): def __init__(self): self.kongfu = '[??煎饼果?配?]' def make_cake(self): print(f'运?{self.kongfu}制作煎饼果?') class Prentice(School, Master): def __init__(self): self.kongfu = '[独创煎饼果?配?]' def make_cake(self): self.__init__() print(f'运?{self.kongfu}制作煎饼果?') def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) # 徒孙类 class Tusun(Prentice): pass xiaoqiu = Tusun() xiaoqiu.make_cake() xiaoqiu.make_school_cake() xiaoqiu.make_master_cake()
  • super(): super()调用父类方法class Master(object): def __init__(self): self.kongfu = '[古法煎饼果?配?]' def make_cake(self): print(f'运?{self.kongfu}制作煎饼果?') class School(Master): def __init__(self): self.kongfu = '[??煎饼果?配?]' def make_cake(self): print(f'运?{self.kongfu}制作煎饼果?') # 方法2.1 # super(School, self).__init__() # super(School, self).make_cake() # 方法2.2 super().__init__() super().make_cake() class Premtice(School): def __init__(self): self.kongfu = '[独创煎饼果子技术]' def make_cake(self): self.__init__() print(f'运用{self.kongfu}制作煎饼果子') # 子类调用父类的同名方法和属性: 把父类的同名属性和方法再次封装 def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) # 一次性调用父类的同名属性和方法 def make_old_cake(self): # 方法一: 代码冗余; 父类类名如果变化, 这里的代码需要频繁修改 # Master.__init__(self) # Master.make_cake(self) # School.__init__(self) # School.make_cake(self) # 方法二: super() # 方法2.1 super(当前类名, self).函数() # super(Prentice, self).__init__() # super(Prentice, self).make_cake() # 方法2.2 super().函数 super.__init__() super.make_cake() daqiu = Prentice() daqiu.make_old_cake() # 注意: 使用super()可以自动查找父类,调用顺序遵循__mro__类属性的顺序. 比较适合单继承使用
  • 私有属性和私有方法定义私有属性和方法: 在Python中 , 可以为实例属性和方法设置私有权限 , 即设置某个实例属性或实例方法不继承给子类class Master(object): def init(self): self.kongfu = '[古法煎饼果?配?]'def make_cake(self): print(f'运?{self.kongfu}制作煎饼果?')class School(object): def init(self): self.kongfu = '[??煎饼果?配?]'def make_cake(self): print(f'运?{self.kongfu}制作煎饼果?')class Prentice(School, Master): def init(self): self.kongfu = '[独创煎饼果子配方]' # 定义私有属性 self.__money = 2000000


    推荐阅读