OOP属性定义

Vít*_*rka 2 python oop python-2.7

我想在方法中定义一个属性:

\n\n
class variables:\n    def definition(self):\n        self.word = "apple"\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后我想使用定义的属性:

\n\n
test = variables()\nprint test.definition.word\n
Run Code Online (Sandbox Code Playgroud)\n\n

我没有写,而是\'apple\'收到错误:

\n\n
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\'\n
Run Code Online (Sandbox Code Playgroud)\n

Art*_*ans 5

  1. definition是一个方法,所以你需要执行它
  2. 因为您正在将变量分配给 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)