程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

@propert decorator for python

編輯:Python

首先,@propertThe role is to put the method in the class『變成』了屬性,Easy to access by instance.propertThere are two usages:You can turn a method into a read-only property;Some properties can be filtered.

想象這樣一個場景,after instantiating a class,A property of the class needs to be assigned a value,At this time, the value assigned to the attribute attribute is not judged,If the property is given an inappropriate value,Then the code will report an error when it is executed later,為了避免這種情況,可以有兩種方法解決.

一:設置一個方法,對屬性值進行判斷:

class Student():
def get_score(self):
return self._score
def set_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
if __name__ == '__main__':
s = Student()
s.set_score(value="88")
print(s.get_score())

再Student類中,為了避免直接對 _score 屬性操作,我們提供了 get_score 和 set_score 方法,這樣起到了封裝的作用,把一些不想對外公開的屬性隱蔽起來,而只是提供方法給用戶操作,在方法裡面,我們可以檢查參數的合理性等.這樣做沒什麼問題,But we have an easier way to do it.

二:使用propert裝飾器.

class Teacher():
@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
if __name__ == '__main__':
t = Teacher()
t.score = 10
print(t.score)
t.score = 20
print(t.score)

在上面,我們給方法 score 加上了 @property,於是我們可以把 score 當成一個屬性來用,此時,A new decorator is created again score.setter,它可以把被裝飾的方法變成屬性來賦值.

另外,We don't have to use either score.setter 這個裝飾器,這時 score It becomes a read-only property:

''' 學習中遇到問題沒人解答?小編創建了一個Python學習交流群:711312441 尋找有志同道合的小伙伴,互幫互助,群裡還有不錯的視頻學習教程和PDF電子書! '''
class test():
def __init__(self, s1):
self.s = s1
@property
def f1(self):
return self.s
if __name__ == '__main__':
t1 = test(s1=90)
print(t1.f1)

注意:last lineprint(t1.f1)不要加括號,print(t1.f1()),要不會報錯’int’ object is not callable


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved