如果在一個(gè)類(lèi)中要設(shè)置和獲取一個(gè)成員變量的話,正常的寫(xiě)法應(yīng)該是以下這種經(jīng)典的寫(xiě)法。
class Student(object):
__slots__ = ('__name', '__age', '__score')
def __init__(self, name, age, score = 0):
self.__name = name
self.__age = age
self.__score = score
# 獲取score
def getscore(self):
return self.__score
# 設(shè)置score value
def setscore(self, score):
if not isinstance(score, int):
raise ValueError('Score必須是int類(lèi)型!')
if score < 0 or score > 100:
raise ValueError('Score值必須在0=<score<=100')
self.__score = score
在實(shí)際的應(yīng)用過(guò)程中,如果要get/set score就得如下這種寫(xiě)法:
stu = Student('Wuli', 28)
stu.setscore(88)
stu.getscore() = 88
這樣這樣寫(xiě)本沒(méi)有什么錯(cuò), 但是鑒于在實(shí)際的碼code的過(guò)程中,getfuncname/setfuncname實(shí)在是太普通了.
我們可能希望get/set一個(gè)值時(shí)有更簡(jiǎn)單的方法(如下),像設(shè)置成員變量一樣去設(shè)置一個(gè)變量,又可以檢查類(lèi)型參數(shù),如下:
#設(shè)置成員變量
stu.score = 100
#獲取成員變量值
stu.score
# 報(bào)錯(cuò):
AttributeError Traceback (most recent call last)
<ipython-input-9-fb8376649a7b> in <module>()
----> 1 stu.__score = 88
AttributeError: 'Student' object has no attribute '__score'
還真可以,因了python有@property 裝飾器。我們對(duì)前面的代碼稍稍做一些修改。
class Student(object):
__slots__ = ('__name', '__age', '__score')
def __init__(self, name, age, score = 0):
self.__name = name
self.__age = age
self.__score = score
# 獲取score
@property
def score(self):
return self.__score
# 設(shè)置score value
@score.setter
def score(self, score):
if not isinstance(score, int):
raise ValueError('Score必須是int類(lèi)型!')
if score < 0 or score > 100:
raise ValueError('Score值必須在0=<score<=100')
self.__score = score
注意一下第1段代碼與第2段代碼之間的差異, get/set的函數(shù)名都變成一樣了。
但是上了分別多了一個(gè)@property/@score.setter.
@property 加了這個(gè)裝飾器的funcname相當(dāng)于getfuncname()
@score.setter 加了這個(gè)裝飾器的funcname相當(dāng)于setfuncname
自此,你就可以像耍成員變量一樣的去耍它們了。
In [15]: stu = Student('wuli2', 28)
In [16]: stu.score = 88
In [17]: print(stu.score)
88