这是一个基本的Python问题。很久以前我看到过这样的东西,我相信它是在Python中。是可能的,还是我错了?
我想要办法做到这一点;下面的例子只是虚构的代码,说明它是如何工作的,但不是。
class SomeClass:
def someMethod(self):
return self.name + ' ' + self.id
name = 'A name'
id = '37'
fullClassName = someMethod # reading this attribute would actually call the method
>>> a = SomeClass()
>>> print a.fullClassName # no parentheses as it's not a method call
A name 37
答案 0 :(得分:2)
您正在寻找property。
>>> class SomeClass:
... name = 'A name'
... id = '37'
...
... @property
... def someMethod(self):
... return self.name + ' ' + self.id
...
... fullClassName = someMethod
...
>>> a = SomeClass()
>>> print a.fullClassName
A name 37
>>>
或只是
>>> class SomeClass:
... name = 'A name'
... id = '37'
...
... @property
... def fullClassName(self):
... return self.name + ' ' + self.id
...
>>> a = SomeClass()
>>> print a.fullClassName
A name 37
>>>