python 的物件繼承
物件的繼承關係( inheritance),可簡化繁複設計的程式碼,讓物件保留母物件的屬性及方法,並可以加上或修改自己的屬性與方法,這種方式大大提高程式設計的效率,繼承的方法就是在物件類別名稱後的小括號中,放入要繼承的物件類別名稱(如Student物件類別繼承了object物件。
number=''
def __init__(self,number):
self.number=number
self.__initSomething()
def set_number(self,number):
self.number=number
def get_number(self):
return self.number
def __initSomething(self):
print 'init something....'
class TimeWorker(Student):
__name=''
def __init__(self,number,name):
self.number=number
self.__name=name
def set_name(self,name):
self.__name=name
def get_name(self):
return self.__name
>>> tw=TimeWorker('N95050005','eric')
>>> tw.get_number()
'N95050005'
>>> tw.get_name()
'eric'
注意:若是要被繼承物件中的成員時,可使用super( )方法呼叫母類別方法或屬性,如要呼叫母類別的__init__設定建構子,放入初始值。
class Student(object):
__number=''
def __init__(self,number):
self.__number=number
self.__initSomething()
def set_number(self,number):
self.__number=number
def get_number(self):
return self.__number
def __initSomething(self):
print 'init something....'
class TimeWorker(Student):
__name=''
def __init__(self,number,name):
super(TimeWorker,self).__init__(number)
self.__name=name
def set_name(self,name):
self.__name=name
def get_name(self):
return self.__name
>>> tw=TimeWorker('N95050005','eric')
init something....
>>> tw.get_number()
'N95050005'