Python 面向对象(中)
生活随笔
收集整理的這篇文章主要介紹了
Python 面向对象(中)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在python中面向?qū)ο蟮娜筇卣?#xff1a;
封裝,繼承,多態(tài)
1. 析構(gòu)方法
程序結(jié)束后,之后調(diào)用析構(gòu)方法,來釋放空間
def __del__(self):print("析構(gòu)方法")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() 吃 四條腿重寫就是在子類中的方法,會(huì)覆蓋父類的方法
4.多態(tài)
對(duì)不同的子類對(duì)象有不同的行為表現(xiàn)
要想實(shí)現(xiàn)多態(tài)必須有兩個(gè)前提:
1.繼承:必須存在繼承關(guān)系,發(fā)生在父類和子類之間
2.重寫:子類需要重寫父類的方法
5 類屬性和實(shí)力屬性
class student:name='黎明' #類屬性def __init__(self,age): #實(shí)例屬性self.age=agelm=student(18) print(lm.name) #通過實(shí)例對(duì)象訪問類屬性 print(lm.age) print(student.name) #通過類對(duì)象訪問類屬性 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.類方法和實(shí)例方法
class people:country='china'@classmethoddef get_country(cls):return cls.country # 訪問類屬性@staticmethoddef getData():return people.country#類方法 print(people.get_country()) #通過類對(duì)象調(diào)用 print(people.country) p=people() print(p.get_country()) # 通過實(shí)例對(duì)象訪問 people.country='chinachina' print(p.country)# 靜態(tài)方法 print(p.getData()) china china china chinachina chinachina靜態(tài)方法中不涉及到類中方法和屬性的操作
數(shù)據(jù)資源能夠得到有效的利用
總結(jié)
以上是生活随笔為你收集整理的Python 面向对象(中)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通信设备包括哪些 有线通信和无线通信
- 下一篇: 粤通宝余额怎么转到e钱包