我有一个示例类。我可以从Python中的变量调用方法吗?
class example(object):
# ...
def size(self):
return somevalue
我怎样才能在instance.size()
代替了size
值由instance.size
没有指定一个新的变量size
?
我有一个示例类。我可以从Python中的变量调用方法吗?
class example(object):
# ...
def size(self):
return somevalue
我怎样才能在instance.size()
代替了size
值由instance.size
没有指定一个新的变量size
?
你应该用户@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'
使用@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
加上包装'@ property'方法https://www.programiz.com/python-programming/property – CasualDemon
上面我不明白你想要做什么。你能写出一些伪代码来显示你想要做什么吗? – skrrgwasme
包装 - >装饰 –