Vít*_*rka 2 python oop python-2.7
我想在方法中定义一个属性:
\n\nclass variables:\n def definition(self):\n self.word = "apple"\nRun Code Online (Sandbox Code Playgroud)\n\n然后我想使用定义的属性:
\n\ntest = variables()\nprint test.definition.word\nRun Code Online (Sandbox Code Playgroud)\n\n我没有写,而是\'apple\'收到错误:
Traceback (most recent call last):\n File "bezejmenn\xc3\xbd.py", line 6, in <module>\n print test.definition.word\nAttributeError: \'function\' object has no attribute \'word\'\nRun Code Online (Sandbox Code Playgroud)\n
definition是一个方法,所以你需要执行它因为您正在将变量分配给 self,所以您可以通过实例访问它,如下所示
test = variables()
test.definition()
print test.word
Run Code Online (Sandbox Code Playgroud)一些想法:
definition方法扩展你的类,object因为python 中的一切都是对象(仅限 python 2.x)
class Variables(object):
def __init__(self):
self.word = 'I am a word'
variables = Variables()
print variables.word
Run Code Online (Sandbox Code Playgroud)