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

# 定义私有方法 def __info_print(self): print(self.kongfu) print(self.__money) 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): passdaqiu = Prentice()对象不能访问私有属性和私有方法print(daqiu.__money)daqiu.__info_print()xiaoqiu = Tusun()子类无法继承父类的私有属性和私有方法print(xiaoqiu.__money) # 无法访问实例属性__moneyxiaoqiu.__info_print()注意: 私有属性和私有方法只能在类里面访问和修改 2. 获取和修改私有属性值:在Python中 , 一般定义函数名get_xx用来获取私有属性,定义set_xx用来修改私有属性值 ```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 # 获取私有属性 def get_money(self): return self.__money # 修改私有属性 def set_money(self): self.__money = 500 def __info_print(self): print(self.kongfu) print(sekf.__money) 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 daqiu = Prentice() xiaoqiu = Tusun() # 调用get_moen函数获取私有属性money的值 print(xiaoqiu.get_money()) # 调用set_moeny函数修改私有属性money的值 xiaoqiu.set_money() print(xiaoqiu.get_money())多态

  • 多态的概念:多态指的是一类事物有多种形态(一个抽象类有多个子类,因而多态的概念依赖于继承)定义: 多态是一种使用对象的方式, 子类重写父类方法, 调用不同子类对象的相同父类方法 , 可以产生不同的执行结果好处:调用灵活,有了多态,更容易编写出通用的代码, 做出通用的编程,以适应需求的不断变化实现步骤:定义父类 , 并提供公共方法定义子类, 并重写父类方法传递子类对象给调用者 , 可以看到不同子类的执行效果不同
  • 例如:class Dog(object): def work(self): # 父类提供统一的方法,哪怕是空方法 print('指哪打哪...') class ArmyDog(Dog): # 继承Dog类 def work(self): # 子类重写父类同名方法 print('追击敌人...') class DrugDog(Dog): def work(self): print('追查毒品...') class Person(object): def work_with_dpg(self, dog): # 传入不同的对象,执行不同的代码,即不同的work函数 dog.work() ad = ArmyDog() dd = DrugDog() daqiu = Person() daqiu.work_with_dog(ad) daqiu.work_with_dog(dd)
类装饰器
  • __call__方法的使用__call__方法:一个类里面一旦实现了__call__方法那么这个类创建的对象就是一个可调用对象 , 可以像调用函数一样进行调用
property属性