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

我可以从Python中的变量调用方法吗?,python,class,Python,Class,我有一个例子课 class example(object): # ... def size(self): return somevalue 如何通过instance.size而不是instance.size()获得size值,而不指定新变量size?您应该使用@property装饰器 使用@property显然更惯用,但为了完整性起见,这是幕后发生的事情 在Python中,当从对象请求不存在的字段时,会调用\uuuu getattr\uuuu魔术方法 clas

我有一个例子课

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

如何通过
instance.size
而不是
instance.size()
获得
size
值,而不指定新变量
size

您应该使用
@property
装饰器


使用
@property
显然更惯用,但为了完整性起见,这是幕后发生的事情

在Python中,当从对象请求不存在的字段时,会调用
\uuuu getattr\uuuu
魔术方法

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

通过在方法上方添加包装器
@property
,我不明白您想做什么。你能写出一些伪代码来显示你想要做什么吗
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