我可以从Python中的变量调用方法吗?

时间:2017-10-09 16:03:10

标签: python class

我有一个示例类。

class example(object):
    # ...
    def size(self):
        return somevalue

如果没有分配新变量size,如何在instance.size之前取代instance.size()值而不是size

2 个答案:

答案 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