class Duck():
def __init__(self, input_name):
self.hidden_name = input_name
def get_name(self):
print('inside the getter')
return self.hidden_name
def set_name(self, input_name):
print('inside the setter')
self.hidden_name = input_name
name = property(get_name, set_name) # property將get_name轉換為getter方法,set_name為setter方法
a = Duck('hhh')
print(a.name) # 會自動調用get_name,打印inside the getter並返回hhh
print(a.hidden_name) # 仍然可以直接訪問hidden_name
class Duck():
def __init__(self, input_name):
self.hidden_name = input_name
@property
def name2(self): # 另外一種設置getter方法的方法
print('inside the getter')
return self.hidden_name
@name2.setter
def set(self, input_name): # setter方法
print('inside the setter')
self.hidden_name = input_name
a = Duck('hhh')
print(a.name2)
class Circle():
def __init__(self, radius):
self.radius = radius
@property
def diameter(self): # 將方法轉換為屬性
return 2 * self.radius
c = Circle(5)
print(c.diameter) # 返回10
c.radius = 7
print(c.diameter) # 可動態計算,返回14
try:
c.diameter = 15 # 因為沒有在類中指定setter方法@diameter.setter,所以無法從外部設置
except Exception as exc:
print(exc)
class Circle():
def __init__(self, radius):
self.radius = radius
self.diameter = 2 * self.radius
c = Circle(5)
print(c.diameter) # 返回10
c.radius = 7
print(c.diameter) # 不可動態計算,返回10
參考資料:《Python語言及其應用》【美】盧巴諾維奇 著
Better reading experience Pyth
1、 find Main.sublime-menu file