简体   繁体   English

OOP属性定义

[英]OOP attribute definition

I want to define an attribute in a method: 我想在方法中定义一个属性:

class variables:
    def definition(self):
        self.word = "apple"

Then I want to use the defined attribute: 然后,我想使用定义的属性:

test = variables()
print test.definition.word

Instead of writing 'apple' I get an error: 我没有写'apple'而是得到一个错误:

Traceback (most recent call last):
  File "bezejmenný.py", line 6, in <module>
    print test.definition.word
AttributeError: 'function' object has no attribute 'word'
  1. definition is a method so you need to execute it definition是一种方法,因此您需要执行它
  2. Because you are assigning a variable to self, you can access it through your instance as follows 因为您要为自己分配一个变量,所以可以通过实例通过以下方式访问它

     test = variables() test.definition() print test.word 

A few ideas: 一些想法:

  • It's best practice start class names with a capital letter 最佳做法是使用大写字母开头课程名称
  • If you just want you class to have a field, you don't need your definition method 如果只希望您的班级有一个字段,则不需要definition方法
  • Extend your class with object because everything in python is objects (python 2.x only) 扩展你的类object ,因为一切都在巨蟒对象(Python的2.X只)

     class Variables(object): def __init__(self): self.word = 'I am a word' variables = Variables() print variables.word 

You can access instance attribute like this: 您可以像这样访问实例属性:

test = variable()
test.definition()
print test.word

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM