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'
definition
is a method so you need to execute it 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:
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.