Python 面向对象(中)
生活随笔
收集整理的这篇文章主要介绍了
Python 面向对象(中)
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
在python中面向对象的三大特征:
封装,继承,多态
1. 析构方法
程序结束后,之后调用析构方法,来释放空间
def __del__(self):print("析构方法")2.单继承
子类继承父类
class animal():def eat(self):print('吃')class dog(animal):#继承父类def wwj(self):print('dog')d=dog() d.eat() 吃3.多继承
class animal():def eat(self):print('吃') class fourleg():def out(self):print('四条腿')class dog(animal,fourleg):#继承父类def wwj(self):print('dog')d=dog() d.eat() d.out() 吃 四条腿重写就是在子类中的方法,会覆盖父类的方法
4.多态
对不同的子类对象有不同的行为表现
要想实现多态必须有两个前提:
1.继承:必须存在继承关系,发生在父类和子类之间
2.重写:子类需要重写父类的方法
5 类属性和实力属性
class student:name='黎明' #类属性def __init__(self,age): #实例属性self.age=agelm=student(18) print(lm.name) #通过实例对象访问类属性 print(lm.age) print(student.name) #通过类对象访问类属性 print(student.age) 黎明 18 黎明 Traceback (most recent call last):File "D:/index.py", line 190, in <module>print(student.age) AttributeError: type object 'student' has no attribute 'age'6.类方法和实例方法
class people:country='china'@classmethoddef get_country(cls):return cls.country # 访问类属性@staticmethoddef getData():return people.country#类方法 print(people.get_country()) #通过类对象调用 print(people.country) p=people() print(p.get_country()) # 通过实例对象访问 people.country='chinachina' print(p.country)# 静态方法 print(p.getData()) china china china chinachina chinachina静态方法中不涉及到类中方法和属性的操作
数据资源能够得到有效的利用
总结
以上是生活随笔为你收集整理的Python 面向对象(中)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 通信设备包括哪些 有线通信和无线通信
- 下一篇: python基本命令range_Pyth