零基础小白入门必看篇:学习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属性property属性就是负责把类中的一个方法当做属性进行使用,这样做可以简化代码的使用class Person(object): def __init__(self): self.__age = 0 # 装饰器方式的property, 把age方法当做属性来使用,表示当获取属性时会执行下面修饰的方法
推荐阅读
- 苹果两款新iPad齐曝光:性能提高、入门款更轻薄、售价便宜
- RHEL 9提升了x86_64处理器的入门要求
- 视频小白们的外挂装备:百视悦R5监视器+T2提词器套装上手
- 市科委与联影集团联合首设“探索者计划”,共推基础及应用基础研究
- 入门HiFi享好声,这几款耳机绝对值得入手
- 从事Java开发时发现基础差,是否应该选择辞职自学一段时间
- 大力发展新型基础设施建设“数字浙江”再添新引擎
- 「新书推荐」5G安全:5G生态的重要组成部分和5G发展的关键基础条件
- DIY从入门到放弃:电源挑贵的买就靠谱吗?
- 微软Surface Pro 8基础版规格或升级 酷睿i3+8GB运存