装饰器
装饰器(decorator)可以给函数动态加上功能。
对于类的方法,装饰器一样起作用。Python内置的@property装饰器就是负责把一个方法变成属性。
直观点,搞了实例后,调用方法可以不加括号()。
另: https://blog.csdn.net/guofeng_hao/article/details/84645277
>>> class Student(object):
... def __init__(self, name, score):
... self.name = name
... self.__score = score
... @property
... def score(self):
... return self.__score
... @score.setter
... def score(self, score):
... if score < 0 or score > 100:
... raise ValueError('invalid score')
... self.__score = score
...
>>> s = Student('Bob', 59)
>>> s.score
59
>>> s.score
59
>>> s.score = 70
>>> s.score
70
>>> s.score = 1000
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in score
ValueError: invalid score
>>> class Student(object):
... def __init__(self, name, score):
... self.name = name
... self.__score = score
... def score(self):
... return self.__score
... def score(self, score):
... if score < 0 or score > 100:
... raise ValueError('invalid score')
... self.__score = score
...
>>> s = Student('Bob', 59)
File "<stdin>", line 1
s = Student('Bob', 59)
^
IndentationError: unexpected indent
>>> s = Student('Bob', 59)
>>> s.score
<bound method Student.score of <__main__.Student object at 0x7f74da2db7b8>>
>>> s.score()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: score() missing 1 required positional argument: 'score'
>>> s.score(70)
>>> s.score()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: score() missing 1 required positional argument: 'score'
浙公网安备 33010602011771号