class ClassName:
<statement-1>
.
.
.
<statement-N>
類對象
#!/usr/bin/python3
class MyClass:
"""一個簡單的類實例"""
i = 12345
def f(self):
return 'hello world'
# 實例化類
x = MyClass()
# 訪問類的屬性和方法
print("MyClass 類的屬性 i 爲:", x.i)
print("MyClass 類的方法 f 輸出爲:", x.f())
輸出結果:
MyClass 類的屬性 i 爲: 12345
MyClass 類的方法 f 輸出爲: hello world
類方法
- 在類地內部,使用 def 關鍵字來定義一個方法,與一般函數定義不同,類方法必須包含參數 self, 且爲第一個參數,self 代表的是類的實例。
#!/usr/bin/python3
#類定義
class people:
#定義基本屬性
name = ''
age = 0
#定義私有屬性,私有屬性在類外部無法直接進行訪問
__weight = 0
#定義構造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 說: 我 %d 歲。" %(self.name,self.age))
# 實例化類
p = people('csdn',10,30)
p.speak()
輸出結果:
csdn 說: 我 10 歲。
類的繼承
class DerivedClassName(BaseClassName1):
<statement-1>
.
.
.
<statement-N>
實例
#!/usr/bin/python3
#類定義
class people:
#定義基本屬性
name = ''
age = 0
#定義私有屬性,私有屬性在類外部無法直接進行訪問
__weight = 0
#定義構造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 說: 我 %d 歲。" %(self.name,self.age))
#單繼承示例
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#調用父類的構函
people.__init__(self,n,a,w)
self.grade = g
#覆寫父類的方法
def speak(self):
print("%s 說: 我 %d 歲了,我在讀 %d 年級"%(self.name,self.age,self.grade))
s = student('ken',10,60,3)
s.speak()
輸出結果:
ken 說: 我 10 歲了,我在讀 3 年級
多繼承
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
實例
#!/usr/bin/python3
#類定義
class people:
#定義基本屬性
name = ''
age = 0
#定義私有屬性,私有屬性在類外部無法直接進行訪問
__weight = 0
#定義構造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 說: 我 %d 歲。" %(self.name,self.age))
#單繼承示例
class student(people):
grade = ''
def __init__(self,n,a,w,g):
#調用父類的構函
people.__init__(self,n,a,w)
self.grade = g
#覆寫父類的方法
def speak(self):
print("%s 說: 我 %d 歲了,我在讀 %d 年級"%(self.name,self.age,self.grade))
#另一個類,多重繼承之前的準備
class speaker():
topic = ''
name = ''
def __init__(self,n,t):
self.name = n
self.topic = t
def speak(self):
print("我叫 %s,我是一個演說家,我演講的主題是 %s"%(self.name,self.topic))
#多重繼承
class sample(speaker,student):
a =''
def __init__(self,n,a,w,g,t):
student.__init__(self,n,a,w,g)
speaker.__init__(self,n,t)
test = sample("Tim",25,80,4,"Python")
test.speak() #方法名同,默認調用的是在括號中排前地父類的方法
輸出結果
我叫 Tim,我是一個演說家,我演講的主題是 Python
方法重寫
#!/usr/bin/python3
class Parent: # 定義父類
def myMethod(self):
print ('調用父類方法')
class Child(Parent): # 定義子類
def myMethod(self):
print ('調用子類方法')
c = Child() # 子類實例
c.myMethod() # 子類調用重寫方法
super(Child,c).myMethod() #用子類對象調用父類已被覆蓋的方法
輸出結果
調用子類方法
調用父類方法
私有屬性方法
- 當方法或屬性以__(兩個下劃線)開頭時,這個方法或者屬性爲私有方法或者私有類,不能被外界直接調用或訪問,在類內部使用時加self。
- 例如: self.__private_attrs