使用以下包含 @property 装饰器的示例代码:
class Grade_Calculator(object):
def __init__(self,score):
self.score = score
@property
def grade(self):
if self.score in range(60,70):
grade = 'D'
elif self.score in range(70,80):
grade = 'C'
elif self.score in range(80,90):
grade = 'B'
elif self.score in range(90,101):
grade = 'A'
return grade
@property
def failure(self):
if self.score < 60:
print 'See me'
grade = 'F'
return grade
和一个例子:
g = Grade_Calculator(28)
g.grade
返回一个UnboundLocalError
. 我想打电话来避免这个错误failure()
。grade()
有一个实例:
g = Grade_Calculator(89)
g.failure()
默默地失败。在这种情况下,我想grade()
在内部调用failure()
以充当故障保险。
我已经看到很多关于只是self.method()
打电话的参考资料,但它们对我不起作用,我认为装饰器的存在以某种方式把我搞砸了:
@property
def grade(self):
if self.score < 60:
self.failure()
elif self.score in range(60,70):
grade = 'D'
elif self.score in range(70,80):
grade = 'C'
elif self.score in range(80,90):
grade = 'B'
elif self.score in range(90,101):
grade = 'A'
return grade
g = Grade_Calculator(28)
g.grade
See me
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-667-fb10e6cf27d4> in <module>()
----> 1 g.grade
./sample.py in grade(self)
6 def grade(self):
7 if self.score < 60:
----> 8 self.failure()
9 elif self.score in range(60,70):
10 grade = 'D'
TypeError: 'str' object is not callable
我不明白什么?