類的屬性通撤夏溃可以在init方法里定義:
class Animal(object):
def __init__(self, height):
self.height = height
但是這樣定義不能校驗(yàn)傳入的參數(shù)堆缘,所以通常要把參數(shù)設(shè)置為私有變量娶靡,在變量名前加下劃線:
class Animal(object):
def __init__(self, height):
self._height = height
然而這樣屬性在外部就不可讀寫某抓,這時需要增加get漱凝、set方法:
class Animal(object):
def get_height(self):
return self._height
def set_height(self, value):
if not isinstance(value, float):
raise ValueError("高度應(yīng)該是小數(shù)")
if value < 0 or value > 300:
raise ValueError("高度范圍是0到300cm")
self._height = value
d = Animal()
d.set_height(250.9)
print(d.get_height()) --------------> 250.9
但是這樣在外部調(diào)用時代碼很繁瑣疮蹦,在這里用裝飾器@property簡化get、set方法
class Animal(object):
@property
def height(self):
return self._height
@height.setter
def height(self, value):
if not isinstance(value, float):
raise ValueError("高度應(yīng)該是小數(shù)")
if value < 0 or value > 300:
raise ValueError("高度范圍是0到300cm")
self._height = value
d = Animal()
d.height = 250.9
print(d.height) --------------> 250.9