1. 程式人生 > >python學習第五章

python學習第五章

如果 實例化 == 常見 繼承 print 一個 調用 多繼承

1.繼承

即是一個派生的類(derived class)繼承基類(base class)的字段和方法,繼承也允許把一個 派生類的對象作為 一個基類

對象對待。通俗來講就是方便,繼承前人的代碼,減少工作量,當然這一切是為實現多態解決解決多繼承的尷尬。具體實現如下:

class A:
def __init__(self):
print("the frist number is 1")
def __init__(self):
print("the second number is 2")
class B:
def __init__(self):
print("the three number is 3")
def __init__(self):
print("the four number is 4")
class C(A,B):
def __init__(self):
A.__init__(self)
B.__init__(self)
super(A,self).__init__()
print("C的改造方法")
c=C()

class person:
def __init__(self,name=None,age=None):
self.name=name
self.age=age
def __str___(self):
return "我是{0},今年 {1}".format(self.name,self.age)
def __add__(self, other):
return person(self.name+other.name,self.age+other.age)
def __lt__(self, other):
if self.name==other.name:
return other.age<other.age
else:
return self.name<other.name
# def __cmp__(self, other):
# return self.name
p=person("JXD",20)
p2=person("dongdong",23)
print(p+p2)
print("-----------------")
p3=[person("dongdong",100),person("dong4",123),]
for p in p3:
print(p)
print("------------------")
for p in sorted(p3):
print(p)
2.類中內置的方法
在python中有一些內置的方法,這些方法命名都有著比較特殊的地方(其方法名是以2個下劃線開始然後以2個下滑線結束。)
類中最常見的構造方法和析構方法。
構造方法:__int__(self,....)在生成對象時調用,可以用來進行一些初始化的操作,不需要顯示去調用,系統會默認去執行。
構造方法支持重載,如果用戶沒有重新定義構造方法,系統就會自動執行默認的構造方法
析構方法:__del__(self,...)在釋放對象時調用,支持重載,可以在裏面進行一些釋放資源的操作,不需要顯示調用。
__str__(self):在使用print語句時被調用
__len__(self): 在調用內聯函數len()時被調用
__cmp__(src,dst): 比較倆個數的src和dst時被調用
3.python 調用內部類的兩種方法:
Class Car:#外部類
class Whell#內部類
def run(self):
print(‘car run’)
class Door:
def open(self):
print(‘open door’)
if __name__=="__main__":
car=Car()#實例化外部類
backDoor=Car.Door()#實例化內部類 第一種方法
frontDoor=car.Door()#再次實化Car的內部類 第2種方法
backDoor.open()
frontDoor.open()
wheel=car.whell() Whell()再次實例化內部類
whell.run()#調用內部類的方法

python學習第五章