類的三大特性之繼承
class Animals:
a_type = "哺乳動物"
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def eat(self):
print("%s is eating ...."%self.name)
class Person(Animals):
a_type = "高級動物"
def talk(self):
print("person %s is talking..."%self.name)
def eat(self):
print("person %s is eat zaofan"%self.name)
class Pig(Animals):
def chase_rabbit(self):
print("pig %s chase rabbit..."%self.name)
p = Person("xdd",22,"Man")
p.talk()
p.eat()
print(p.a_type)
pig = Pig("jack",2,"pig")
pig.chase_rabbit()
print(pig.a_type)
重寫父類方法 - 單繼承
# -*- coding:utf-8 -*-
class Animals:
a_type = "哺乳動物"
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def eat(self):
print("%s is eating ...."%self.name)
class Person(Animals):
a_type = "高級動物"
def __init__(self,name,age,sex,hobbie):
#Animals.__init__(self,name,age,sex)
#super(Person,self).__init__(name,age,sex)
super().__init__(name,age,sex)
self.hobbie = hobbie
def talk(self):
print("person %s is talking..."%self.name)
def eat(self):
super().eat() #super繼承執行父類的方法
print("person %s is eat zaofan"%self.name)
class Pig(Animals):
def chase_rabbit(self):
print("pig %s chase rabbit..."%self.name)
p = Person("xdd",22,"Man","read book")
p.talk()
p.eat()
print(p.a_type,p.hobbie)
類的多繼承
按順序從左到右繼承
繼承順序分為兩種:這是簡單的理解,深度理解完全不是這樣的
深度優先:先找M -MB - S -SB
廣度優先: 一層一層的找 先M -S - MB -SB
實際上在python3上類的多繼承的情況下,使用的是C3演算法,既不能說是廣度也不能說是深度
Python 中,類有兩種寫法: 在python 3上默認就是新式類
Class A: #經典類
Class B(object): #新式類
C3演算法十分復雜,所以有興趣去了解
如果想要簡單快速的查看一個類的繼承方式可以使用:
Print(類名.mro())
# -*- coding:utf-8 -*-
class ShenXianBase:
def fight(self):
print("元祖在打架")
class ShenXian(ShenXianBase):
def fly(self):
print("shenxian is fly")
def fight(self):
print("神仙在打架")
class MonkeyBase:
def fight(self):
print("猿猴在打擊")
class Monkey(MonkeyBase):
def eat_peach(self):
print("monkey like eat taozi ")
def fight(self):
print("猴子在打擊")
class Monkeyking(ShenXian,Monkey):
def play_goden_stick(self):
print("sun wu kong play jinjubang")
sxz = Monkeyking()
sxz.eat_peach()
sxz.fly()
sxz.play_goden_stick()
sxz.fight()
print(Monkeyking.mro())
類的三大特性之--封裝 :私有變數都是加兩個下劃線__
self.__name 將變數變成私有的
方法也可以變成私有的
def __sayhi():
# -*- coding:utf-8 -*-
class Person(object):
def __init__(self,name,age):
self.__name = name
self.__age = age
def __get_name(self):
print("name is %s"%self.__name)
p = Person("xdd",22)
print(p._Person__name) #強行訪問私有變數
p._Person__name = "jack" #強行修改私有變數
p._Person__get_name() #強行訪問私有方法
類的三大特性之- 多型
有時一個物件會有多種表現形式,比如網站頁面有button按鈕,可以有正方形的圓的,方的,但是他們有一個共同的呼叫方法onClick()
# -*- coding:utf-8 -*-
#多型
class Dog(object):
def sound(self):
print("wang wang wang ...")
class Pig(object):
def sound(self):
print("heng heng heng ...")
def animals_sound(obj1):
obj1.sound()
d = Dog()
p = Pig()
animals_sound(d)
animals_sound(p)
# -*- coding:utf-8 -*-
#多型2
class Documents(object):
def __init__(self,name):
self.name = name
def show(self):
raise NotImplementedError("Subclass must implement abs")
class Pdf(Documents):
def show(self):
return "show pdf contents"
class Word(Documents):
def show(self):
return "show Word contents"
pdf = Pdf("xixixi.pdf")
word = Word("yyy.word")
obj = [pdf,word]
for o in obj:
print(o.show()) # 這個show方法就是介面上邊的pdf,word就是形態
類方法,靜態方法:
類方法:
類方法通過@classmethod裝飾器來裝飾一下即只能訪問類的變數,不能訪問實體變數
# -*- coding:utf-8 -*-
class Dog(object):
name = 'gouzi'
def __init__(self,name):
self.name = name
@classmethod
def eat(self):
print("dog %s is eating ...."%self.name)
d = Dog("xdd")
d.eat()
為什么不能訪問實體變數,因為傳進來的值不是實體本身,而是類本身,加上classmethod方法就會變成這樣,去掉classmethod,傳進來的就是實體本身了.
作用:
# -*- coding:utf-8 -*-
class Stu(object):
__stu_num = 0
def __init__(self,name):
self.name = name
self.add_stu(self)
@classmethod
def add_stu(cls,obj):
if obj.name:
cls.__stu_num += 1
print("生成一個新學生",cls.__stu_num)
s = Stu('j')
s2 = Stu('k')
s3 = Stu('o')
s4 = Stu('5')
靜態方法:
@staticmethod 既不能訪問實體變數,又不能訪問類變數
靜態方法割斷了他和類或實體的任何關系
屬性方法property
把一個方法變成一個靜態的屬性
class Stu(object):
def __init__(self,name):
self.name = name
@property
def fly(self):
print("jack is flying")
s = Stu('rain')
s.fly #不需要加括號了,呼叫這個方法
神奇的反射:
可以通過字串的形式來操作物件的屬性
Getattr 獲取
Hsaattr 查詢
Setattr 賦值
Delattr 洗掉
如何反射一個檔案下指定的對應的屬性
__name__ 在當前檔案主動執行的情況下(不是被匯入執行),__name__ 就等于 __main__
在被其他檔案當模塊執行的時候,就等于這個檔案(模塊)名
# -*- coding:utf-8 -*-
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def drink(self):
print("drink water ...")
def talk(self):
print("talking...")
p = Person('xdd',22)
#查詢
if hasattr(p,"name"):
print("11111")
user_command = input('>>').strip()
if hasattr(p,user_command):
fun = getattr(p,user_command)
fun()
#獲取
a = getattr(p,"age")
print(a)
#修改,增加
setattr(p,"sex","Man")
print(getattr(p,'sex'))
setattr(Person,"speak",talk)
p.speak()
#洗掉
delattr(p,"age")
if __name__ == "__main__": #只會被在別的模塊匯入的時候發揮作用
print('jaja')
#動態獲取當前模塊下的屬性
import sys
mod = sys.modules["__main__"]
if hasattr(mod,"p"):
o = getattr(mod,"p")
print(o.drink)
動態加載模塊
# -*- coding:utf-8 -*-
#動態加載模塊 ,熱加載,在程式運行中,加入一個模塊
#__import__("Property") #解釋器用的
import importlib
importlib.import_module("Property") #python官方推薦使用的 和上邊的效果是一樣的
importlib.import_module("function_def.List_builder")
反射的再應用:
#-*- coding:utf-8 -*-
class User(object):
def __init__(self):
print("welcome to yingxionglianmeng")
def login(self):
print("login...")
def register(self):
print("zhucejianmian...")
def disk(self):
print("welcome to save disk")
u = User()
while True:
user_cmd = input(">>").strip()
if hasattr(u,user_cmd):
getattr(u,user_cmd)()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/103802.html
標籤:Python
上一篇:linux環境"ModuleNotFoundError: No module named 'Cryptodome'"
下一篇:類的內置方法(用實際代碼來驗證)
