Python 類的定義
1. 初步比較
class people:
# 成員變量 類似java 中的public標識符
name = ' '
age = ' '
# 私有成員變量,類似java中的private標識符
__weight = 0
# 定義構造方法,類似javaz中的構造方法
# 這裏的self 類似java中的 this,實際就是該實例的地址
# self.__class__ 是指向類
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))
# 定義私有方法
def __foo(self):
print('這是私有方法')
# 實例化類
p = people('limm',10,30)
p.speak()
p.foo() # 異常
2. 繼承
class student(people):
grade = ' '
def __init__(self,n,a,w,g):
#類似於super()
people.__init__(self,n,a,w,)
self.grade = g
# 覆寫父類方法
def speak(self)
print("%s 說: 我 %d 歲了,我在讀 %d 年級"%(self.name,self.age,self.grade))
3. 多繼承
class people:
name = ' '
age = ' '
__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() #方法名同,默認調用的是在括號中排前地父類的方法