Smarty77
Smarty77

Reputation: 1358

Python3, using object instance within another class

I'm trying to modify class attribute by reference to object in __init__ method and then use it in another method. Sadly the following code sample doesn't work as expected...

CODE

class Translator:
    #list of attributes
    parser=None
    def __init__(self):   
         parser = Parser_class() ...
         #some other commands
    def Translate(self): 
         something=self.parser.GenerateHead() ...
         #more commands

COMPILE ERR

AttributeError: 'NoneType' object has no attribute 'GenerateHead'

I know that I can give it to the Translate method as argument, I'm just curious why this statement within Python doesn't work.

Upvotes: 2

Views: 543

Answers (1)

Blckknght
Blckknght

Reputation: 104832

You're doing your instance attributes wrong.

First off, you don't need to declare your attributes ahead of time. Putting parser = None at the top level of the class creates a class variable named parser, which I don't think is what you want. Usually in Python you can add new instance attributes at any time by a simple assignment: instance.attr = "whatever".

Second, when you want to do an instance assignment from within a method, you need to use self to refer to the instance. If you leave off self, you'll be assigning to a local variable inside your function, not to an instance or class variable. Actually, the specific name self isn't necessary, but you do need to use the first argument to the method (and it's probably not a good idea to break the convention of naming that self).

So, to fix your code, do this:

class Translator:
    # don't declare variables at class level (unless you actually want class variables)

    def __init__(self):   
         self.parser = Parser_class()   # use self to assign an instance attribute

    def Translate(self): 
         something = self.parser.GenerateHead()  # this should now work

Upvotes: 3

Related Questions