instance attribute "a" defined outside __init__
gordon at panix.com
Wed Apr 1 23:37:25 CEST 2015
In <f8a3fb6e-6878-4aec-9958-5394580ec0e4 at googlegroups.com> Rio <inkprs at gmail.com> writes:
> Hi, When running below code, I get error saying:
> instance attribute "a" defined outside __init__
That's a warning, not an error. And it's a warning from pylint,
not from Python itself.
It's trying to suggest better style, that's all. It's unusual to
define instance variables in functions other __init__.
> class Foo:
> var = 9
> def add(self, a, b):
> self.a = a
> self.b = b
> print a+b
> def __init__(self):
> print 10
> bar = Foo() # create object
> bar.add(4, 7) # call method by object.method
> print bar.var # access class variable
> why the output prints:
10 is printed by Foo.__init__(), when an instance of Foo is created.
11 is printed by calling bar.add(4, 7).
9 is printed by your statement 'print bar.var'.
Your program has those statements in that order, so they are printed
in that order. Why did you expect a different order?
John Gordon Imagine what it must be like for a real medical doctor to
gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'.
More information about the Python-list