简体   繁体   中英

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:

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
  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
  • Extend your class with object because everything in python is objects (python 2.x only)

     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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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