Reputation: 99
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'
Upvotes: 2
Views: 364
Reputation: 4640
definition
is a method so you need to execute itBecause 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
methodExtend 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
Upvotes: 5
Reputation: 324
You can access instance attribute like this:
test = variable()
test.definition()
print test.word
Upvotes: 2