想把屬性設為private 在前面加__
獲取對象信息
type()
我們來判斷對象類型,使用type()函數(shù)
type(123)
#<class 'int'>
但是type()函數(shù)返回的是什么類型呢?它返回對應的Class類型。如果我們要在if語句中判斷,就需要比較兩個變量的type類型是否相同
import types
type(lambda x: x)==types.LambdaType
isinstance
a = Animal()
d = Dog()
isinstance(d, Husky) #True
dir()
dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']
類似xxx的屬性和方法在Python中都是有特殊用途的,比如len方法返回長度。在Python中,如果你調(diào)用len()函數(shù)試圖獲取一個對象的長度,實際上,在len()函數(shù)內(nèi)部,它自動去調(diào)用該對象的len()方法
slot
正常情況下,當我們定義了一個class,創(chuàng)建了一個class的實例后,我們可以給該實例綁定任何屬性和方法,這就是動態(tài)語言的靈活性。
def set_age(self, age): # 定義一個函數(shù)作為實例方法
self.age = age
from types import MethodType
s.set_age = MethodType(set_age, s)
s.set_age(25)
同理,可以給Class綁定方法
Student.set_score = set_score
如果我們想要限制實例的屬性怎么辦?比如,只允許對Student實例添加name和age屬性
class Student(object):
__slots__ = ('name', 'age') # 用tuple定義允許綁定的屬性名稱
s = Student() # 創(chuàng)建新的實例
s.name = 'Michael' # 綁定屬性'name'
s.age = 25 # 綁定屬性'age'
s.score = 99 # 綁定屬性'score' #error
使用slots要注意,slots定義的屬性僅對當前類實例起作用,對繼承的子類是不起作用的
@property
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
s = Student()
>>> s.score = 60 # OK,實際轉(zhuǎn)化為s.set_score(60)
>>> s.score # OK,實際轉(zhuǎn)化為s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
多重繼承
class Runnable(object):
def run(self):
print('Running...')
class Mammal(Animal):
pass
class Dog(Mammal, Runnable):
pass
枚舉類
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))))
如果需要更精確地控制枚舉類型,可以從Enum派生出自定義類:
from enum import Enum,unique
@unique
class Weekday(Enum):
Sun = 0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
@unique裝飾器可以幫助我們檢查保證沒有重復值。