我有一个示例类。
class example(object):
# ...
def size(self):
return somevalue
如果没有分配新变量size
,如何在instance.size
之前取代instance.size()
值而不是size
?
答案 0 :(得分:5)
您应该使用@property
装饰器
https://docs.python.org/2.7/howto/descriptor.html#properties
class example(object):
# ...
@property
def size(self):
return 'somevalue'
example_inst = example()
example_inst.size #'somevalue'
答案 1 :(得分:2)
使用@property
绝对是更惯用的,但为了完整起见,这就是幕后发生的事情。
在Python中,当从对象请求不存在的字段时,将调用__getattr__
魔术方法。
class example(object):
def __getattr__(self, key):
if key == "size":
return somevalue
else:
return super().__getattr__(key) # Python 3.x
# return super(self.__class__, self).__getattr__(key) # Python 2.x