简单了解Python多态与属性运行原理
作者:鸡龟骨滚羹 时间:2021-03-13 21:29:42
1.多态是指传入不同的对象,产生不同的结果
多态指的是一类事物有多种形态(一个抽象类有多个子类,因而多态的概念依赖于继承)
定义:多态是一种使用对象的方法,子类重写父类方法,调用不同子类对象的父类方法,可以产生不同的执行结果
好处:调用灵活,有了多态,更容易编写出通用的代码。
代码展示:
class Dog(object):
def work(self):
print('指哪打哪')
class ArmyDog(Dog):
def work(self):
print('追击敌人')
class DrugDog(Dog):
def work(self):
print('追查 * ')
class Person(object):
def work_with_dog(self, dog):
dog.work()
ad = ArmyDog()
dd = DrugDog()
daqiu = Person()
daqiu.work_with_dog(ad)
daqiu.work_with_dog(dd)
2.类属性就是类对象所拥有的属性,它被该类的所有实例对象所共有
类属性可以使用类对象或实例对象访问。
例如:
class Dog(object):
tooth = 10
wangcai = Dog()
xiaohei = Dog()
print(Dog.tooth)
print(wangcai.tooth)
print(xiaohei.tooth)
得出的结果都为:10
记录的某项数据始终保持一致时,定义类属性
实例属性要求每个对象为其单独开辟一份内存空间来记录数据,而类属性为全类所共有,仅占用一份内存,更加节省内存空间。
3.修改类属性
类属性只能通过类对象修改,不能通过实例对象修改,如果通过实例对象修改类属性,表示的是创建了一个实例属性
来源:https://www.cnblogs.com/enoch-m/p/13108128.html
标签:Python,多态,属性
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
该用多大的字
2009-05-17 14:39:00
Html的几个小技巧
2011-04-29 14:02:00
基于Python编写一个刷题练习系统
2022-10-01 13:28:34
![](https://img.aspxhome.com/file/2023/2/79442_0s.png)
SQL Server中的执行引擎入门 图解
2012-06-06 20:08:26
escape解决AJAX中文乱码的简单方法
2008-10-23 14:32:00
初瞥 Google Chrome Frame
2009-10-06 14:41:00
![](https://img.aspxhome.com/file/UploadPic/200910/6/medium-75s.jpg)
mysql5在rhel5下乱码问题及解决方法
2010-12-03 16:26:00
![](https://img.aspxhome.com/file/UploadPic/201012/3/2010123165047481s.png)
如何用Response.Write调用代替内嵌表达式?
2010-06-13 14:33:00
Python TypeError: ‘float‘ object is not subscriptable错误解决
2023-09-13 05:33:02
![](https://img.aspxhome.com/file/2023/9/62249_0s.png)
发一段鼠标掠过表格行颜色改变的代码
2010-07-02 12:59:00
python reduce 函数使用详解
2022-11-01 22:20:57
![](https://img.aspxhome.com/file/2023/4/76184_0s.png)
antd项目实现彩蛋效果的详细代码
2023-09-14 12:51:20
![](https://img.aspxhome.com/file/2023/1/56321_0s.jpg)
分享整理的12条sql语句连同数据
2012-07-11 16:14:59
用VB生成DLL封装ASP代码一个例子:连接access数据库等
2008-04-07 13:06:00
Python如何通过变量ID得到变量的值
2023-01-22 22:35:56
![](https://img.aspxhome.com/file/2023/4/65884_0s.jpg)
Pytorch 图像变换函数集合小结
2022-06-14 08:52:09
![](https://img.aspxhome.com/file/2023/9/84929_0s.jpg)
选项卡动态增删的效果(内嵌框架)
2008-05-22 12:59:00
![](https://img.aspxhome.com/file/UploadPic/20085/22/asgard_cardprogram_62s.jpg)
详解Python if-elif-else知识点
2022-02-23 16:06:23
Windows mysql命令行导入 .sql文件
2010-12-03 16:12:00
Golang设计模式中抽象工厂模式详细讲解
2023-08-04 20:46:46
![](https://img.aspxhome.com/file/2023/4/93664_0s.png)