Vítek Peterka
Vítek Peterka

Reputation: 99

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'

Upvotes: 2

Views: 364

Answers (2)

Arturs Vancans
Arturs Vancans

Reputation: 4640

  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
    

Upvotes: 5

Guillaume Pannatier
Guillaume Pannatier

Reputation: 324

You can access instance attribute like this:

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

Upvotes: 2

Related Questions