Dirty Penguin
Dirty Penguin

Reputation: 4402

How to access a method's attribute

Is it possible to access a method's attribute directly? I tried this and it fails:

class Test1:
    def show_text(self):
        self.my_text = 'hello'

Which results in:

>>> t = Test1()
>>> t.my_text
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Test1 instance has no attribute 'my_text'

I found that using this made it work:

class Test1:
    def __init__(self):
        self.my_text = 'hello'

But I'm wondering if it's still possible to access attributes of methods directly? Or am I doing something Very Bad?

Upvotes: 1

Views: 113

Answers (3)

Carlos
Carlos

Reputation: 2232

Instance variables are created once the object has been instantiated and only after they have been assigned to.

class Example(object):
      def doSomething(self):
          self.othervariable = 'instance variable'

>> foo = Example()
>> foo.othervariable
AttributeError: 'Example' object has no attribute 'othervariable'

Since othervariable is assigned inside doSomething - and we haven't called it yet -, it does not exist.

Once we call it, though:

>> foo.doSomething()
>> foo.othervariable
'instance variable'

__init__ is a special method that automatically gets invoked whenever class instantiation happens. Which is why when you assign your variable in there, it is accessible right after you create a new instance.

class Example(object):

      def __init__(self):
          self.othervariable = 'instance variable'

>> foo = Example()
>> foo.othervariable
'instance variable'

Upvotes: 4

DonCallisto
DonCallisto

Reputation: 29912

Your first example didn't work: since you never use show_text() method, your object will never have attribute my_text (that will be "added" to your object only when you invoke that method).

Second example is good, because __init__ method is executed as soon as your object is instantiated.

Moreover, is a good practice to access object attribute through getter method on object itself so the best way you can modify your code is

class Test1:
    def __init__(self,value):
        self.my_text = value
    def show_text(self):
        return self.my_text

and then use in that way

t = Test1('hello')
t.show_text()

At last, will be also good to have a method like this

def set_text(self,new_text):
    self.my_text = new_text

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

my_text attribute doesn't exist until you don't call show_text:

>>> class Test1:
...         def show_text(self):
...                 self.my_text = 'hello'
...         
>>> t  = Test1()
>>> t.show_text()
>>> t.my_text
'hello'

If you want your attributes to be created during instance creation then place them in __init__ method.

Upvotes: 2

Related Questions