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 面向对象(中)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通信设备包括哪些 有线通信和无线通信
- 下一篇: 粤通宝余额怎么转到e钱包