是否可以执行以下操作:
class foo():
def bar(): # a method that doesn't take any args
# slow calculation
return somefloat
b = bar # bar is a function but b just gives you the float attribute
f = foo()
f.b # returns somefloat but doesn't require the empty parentheses
我希望这个例子很清楚,因为我不太清楚我想做什么的术语。我的基本目标是为没有参数的方法删除一堆括号,以使代码更易于阅读。
该函数很慢且很少使用,因此,实时计算而不是预先计算一次并存储变量将是最简单的方法。
这可能吗?这是好习惯吗?有没有更好的办法?
python大神给出的解决方案
实现此目的的标准方法是使用property
,即decorator:
class Foo():
@property
def bar(self):
# slow calculation
return somefloat
f = Foo()
f.bar # returns somefloat but doesn't require the empty parentheses
需要注意的几件事:
您仍然需要像往常一样在方法签名中使用self
,因为有时您需要引用例如方法中的self.some_attribute
。如您所见,这根本不影响该属性的使用。
无需同时使用f.bar()
方法和f.b
属性来使API混乱-与提供大量不同的方法来执行同一操作相比,最好决定什么对您的类最有意义。