1. 程式人生 > >Python——property(使一個方法看起來就像類屬性一樣)

Python——property(使一個方法看起來就像類屬性一樣)

一定要註意了 函數返回 exce 函數 蘋果 調用 prop 存在 ice

""" 裝飾器property: 使一個方法看起來就像類屬性一樣 """ #例子1 class A: def __init__(self, x, y): self.__x = x #私有變量 self.__y = y def __add(self): #私有方法 return self.__x + self.__y @property def sum(self): #通過property裝飾器修飾後將方法看起來就像屬性一樣 return self.__add() if __name__ == '__main__': a = A(5,6) print(a.sum) #外部調用sum,看起來就如同屬性,這個屬性實際上是一個不被計算功能的方法 #例子2 class Foo: @property def foo(self): return "bar" f = Foo() print(f.foo) 例子3 class Foo: @property def foo(self): return self._foo @foo.setter #使用foo方法的setter屬性又裝飾了這個foo方法,這個foo和上面的foo只是名字相同,實際是不同的 def foo(self, value): self._foo = value f = Foo() f.foo = 100 print(f.foo) #一定要註意了,由property裝飾器裝飾後的函數返回的是一個對象 #例子4 class Silly: @property def silly(self): print("You are getting silly") return self._silly #返回的是一個property對象 @silly.setter def silly(self, value): print("You are making silly {}".format(value)) self._silly = value @silly.deleter #刪除函數(目前我也不知道這麽去使用它) def silly(self): print("Whoah you killed silly!") del self._silly s = Silly s.silly = 100 print(s.silly) #再看最後的一個例子,一個蘋果類中的價格屬性 class Apple: def __init__(self, price): self.price = price a = Apple(19) print(a.price) a.price = 20 #隨意被更改了,存在數據安全問題 print(a.price) #改進代碼v1.0 class Apple: def __init__(self, price): self._price = price #將屬性增加單下劃線,變成半保護 a = Apple(19) #初始化價格 print(a._price) #打印 a.price = 25 #嘗試的修改 print(a._price) #貌似沒有修改成功,還是原來的19 #繼續改進 v1.0.1 class Apple: def __init__(self, price): self._price = price a = Apple("hello") #price是價格,但被人傳入的是字符串,也就是說被隨意傳入不同的數據類型的數據,需要繼續改進 print(a._price) #繼續改進 v1.0.2 class Apple(object): def get_price(self): return self.__price def set_score(self, price): if not isinstance(price, int): raise ValueError('Price must be an integer!') self.__price = price a = Apple() a.set_score(19) #那麽可以再試試傳入字符串,那麽則會引發異常 print(a.get_price()) #最終版本 v2.0 class Apple(object): @property def get_price(self): try: return self.__price except AttributeError: print("No Data...") @get_price.setter #@property本身又創建了另一個裝飾器@get_price.setter,負責把一個setter方法變成屬性賦值 def set_score(self, price): if not isinstance(price, int): raise ValueError('Price must be an integer!') self.__price = price a = Apple() a.set_score = 20 print(a.get_price)


Python——property(使一個方法看起來就像類屬性一樣)