?
繼承一個類
class Person(object):
??? def __init__(self, name, gender):
??????? self.name = name
??????? self.gender = gender
?
class Student(Person):
??? def __init__(self, name, gender, score):
??????? super(Student, self).__init__(name, gender)
??????? self.score = score
?
判斷類型
isinstance()可以判斷類型
isinstance(p, Person)
?
多態
動態語言和靜態語言(例如java)的最大差別是,不檢查類型,只要方法存在,參數正確,就可以調用。
?
支持多重繼承
?
獲取對象信息
type()??? # 獲取對象類型
dir()??? # 獲取變量所有屬性字符串list,可結合filter()獲得定制的屬性列表
?
已知屬性名:
getattr(s, 'name')
setattr(s, 'name', 'Adam')
?
?
特殊方法
定義在class中,不需要直接調用,Python的某些函數或操作符會調用對應的特殊方法。
?
__getattr__
?
__setattr__
__delattr__
?
__str__??? # 給print看的信息
__repr__??? # 給開發人員看的信息
__cmp__??? #排序用
__len__??? #讓len()函數正常工作的話,就必須定義此方法,返回元素個數
?
四則運算:
__add__
__sub__
__mul__
__div__
?
__int__??? #讓int()函數工作
__float__??? #讓float()函數工作
?
?
__slots__??? #一個類允許的屬性列表,即限制當前類所能擁有的屬性
class Student(object):
??? __slots__=('name', 'gender', 'score')
??? def __init__(self, name, gender, score):
??????? self.name = name
??????? self.gender = gender
??????? self.score = score
?
__call__??? #將實例變爲可調用對象
在Python中,函數其實是一個對象;
所有的函數都是可調用對象;
一個類實例也可以變成一個可調用對象,只需要實現一個特殊方法__call__()
例子:把Person類實例變成一個可調用對象:
class Person(object):
??? def __init__(self, name, gender):
??????? self.name = name
??????? self.gender = gender
???
??? def __call__(self, friend)
??????? print 'My name is %s...' % self.name
??????? print 'My friend is %s...' % friend
?
>>> p = Person('Bob', 'male')
>>> p('Tim')
My name is Bob...
My friend is Tim...
?
對私有屬性的訪問
用get/set方法來封裝對一個屬性的訪問在許多面向對象編程的語言中都很常見。
但是寫s.get_score()和s.set_score()方法沒有寫s.score來的直接。
可以用裝飾器函數
class Student(object):
??? def __init__(self, name, score):
??????? self.name = name
??????? self.__score = score
??? @property
??? def score(self):
??????? return self.__score
??? @score.setter
??? def score(self, score):
??????? if score < 0 or score > 100:
??????????? raise ValueError('invalid score')
??????? self.__score = score
?
第一個score(self)是get方法,用@property裝飾
第二個score(self, score)是set方法,用@score.setter裝飾,是@property裝飾后的副產品。
現在就可以像使用屬性一樣設置score了。
?
?
?
?
?