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