python - Python3, using object instance within another class -
i'm trying modify class attribute reference object in __init__
method , use in method. sadly following code sample doesn't work 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 can give translate
method argument, i'm curious why statement within python doesn't work.
you're doing instance attributes wrong.
first off, don't need declare attributes ahead of time. putting parser = none
@ top level of class creates class variable named parser
, don't think want. in python can add new instance attributes @ time simple assignment: instance.attr = "whatever"
.
second, when want instance assignment within method, need use self
refer instance. if leave off self
, you'll assigning local variable inside function, not instance or class variable. actually, specific name self
isn't necessary, need use first argument method (and it's not idea break convention of naming self
).
so, fix code, this:
class translator: # don't declare variables @ class level (unless want class variables) def __init__(self): self.parser = parser_class() # use self assign instance attribute def translate(self): = self.parser.generatehead() # should work
Comments
Post a Comment