# 類的特點(diǎn) 封裝 繼承 多肽(不常用)
#繼承:一個(gè)類繼承另一個(gè)類,就可以使用另一個(gè)類里的方法
eg
class Father1:
? ? def hello(self):
? ? ? ? print('hello')
class Father(object):#object->Father->son
? ? def __init__(self,name):#父類的屬性高于兩個(gè)子類
? ? ? ? self.name=name
? ? def eat(self):
? ? ? ? print('大吃一頓')
class Son1(Father,Father1):#繼承Father類,可同時(shí)繼承多個(gè)父類
? ? name='小黑'
class Son2(Father):#繼承中,訪問(wèn)的順序逐層son->father->object
? ? name='小白'
son1=Son1('小白')
son2=Son2('小黑')
print(son1.name)
son1.eat()
son1.hello()
print(Father.__bases__)#__bases__查詢其父類名
print(son2.name)
son2.eat()
#如果繼承多個(gè)父類 父類中有同種方法 會(huì)優(yōu)先繼承最左變得類
#繼承優(yōu)先級(jí) 由左到右
class Father:
? ? def __init__(self,name):
? ? ? ? self.name=name
? ? def eat(self):
? ? ? ? print("大吃一頓")
class Mother:
? ? def __init__(self,age,sex):
? ? ? ? self.age=age
? ? ? ? self.sex=sex
? ? def cook(self):
? ? ? ? print('炒菜好吃%s'%self.age)
class son(Father,Mother):
? ? pass
xiaohong=son('name')#此時(shí)參數(shù)不會(huì)傳入Mother中
print(xiaohong.name)
xiaohong.eat()
xiaohong.age='age'#可使用此方法向Mother傳參
print(xiaohong.age)
xiaohong.cook()
class Base:
? ? def play(self):
? ? ? ? print('this is base')
class A(Base):
? ? def play(self):
? ? ? ? print('this is A')
? ? ? ? super().play()#調(diào)用B,
class B(Base):
? ? def play(self):
? ? ? ? print('this is B')
class Son(A,B):
? ? def play(self):
? ? ? ? print('this is Son')
? ? ? ? Base().play()#可用于調(diào)用父類
? ? ? ? super().play()#super.方法()調(diào)用父類的方法 遵循mro規(guī)則
#mro 算法解析順序 繼承的順序,
s=Son()#實(shí)例化Son,mro規(guī)則順序?yàn)?A->B-Base->object
s.play()
print(Son.__mro__)#通過(guò)此語(yǔ)句可以查看mro順序
A().play()
#在使用類里方法的時(shí)候 有兩種形式
#1,實(shí)例化一個(gè)對(duì)象 通過(guò)對(duì)象.方法()
#2,類名().方法()? #類名()? 實(shí)例化
#不想使用父類方法,可在子類中重寫(xiě)進(jìn)行覆蓋
#多繼承? Mix-in(搭積木)設(shè)計(jì)模式-->由分到總
# 魔法方法
#運(yùn)算符方法參考+這種
class A:
? ? def __init__(self,num1,num2):
? ? ? ? self.num1=num1
? ? ? ? self.num2=num2
? ? def __add__(self,other):#由+號(hào)調(diào)用
? ? ? ? sum1=self.num1+other.num2
? ? ? ? sum2=self.num2+other.num1
? ? ? ? return sum1,sum2
? ? ? ? print(sum1)
a=A(10,100)
b=A(11,111)
print(a+b)
print(1+2)
# str 和 repr (必須返回字符串)
#print 直接打印對(duì)象時(shí),會(huì)顯示object和地址
#如果定義了repr,print打印時(shí)會(huì)打印這個(gè)魔法方法里的內(nèi)容
#如果定義了str就會(huì)打印str里的內(nèi)容
#str和repr同時(shí)出現(xiàn),只會(huì)打印str里的內(nèi)容
class Person:
? ? def play(self):
? ? ? ? print('this is play')
? ? def __str__(self):
? ? ? ? return 'this is str'
? ? def __repr__(self):
? ? ? ? return 'this is repr'
x=Person()
x.play()
# %s 占位符 %r也是占位符
# %s 會(huì)調(diào)用str %r會(huì)調(diào)用repr
print('%s'%x)#打印時(shí)默認(rèn)為str
print('%r'%x)#交互時(shí)默認(rèn)為repr
# __str__返回的結(jié)果 可讀性強(qiáng) 方便閱讀者
# __repr__返回的結(jié)果更精確? 方便開(kāi)發(fā)者
# __call__方法
class Person:
? ? #實(shí)例變量加上括號(hào)就可以調(diào)用__call__
? ? def __call__(self):
? ? ? ? print('this is call')
h=Person()
h.age=19
h()
print(h.__class__)#查詢類名
print(h.__dict__)#以字典形式輸出實(shí)例屬性?