Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #88432 > unrolled thread
| Started by | Rio <inkprs@gmail.com> |
|---|---|
| First post | 2015-04-01 14:26 -0700 |
| Last post | 2015-04-01 21:37 +0000 |
| Articles | 2 — 2 participants |
Back to article view | Back to comp.lang.python
instance attribute "a" defined outside __init__ Rio <inkprs@gmail.com> - 2015-04-01 14:26 -0700
Re: instance attribute "a" defined outside __init__ John Gordon <gordon@panix.com> - 2015-04-01 21:37 +0000
| From | Rio <inkprs@gmail.com> |
|---|---|
| Date | 2015-04-01 14:26 -0700 |
| Subject | instance attribute "a" defined outside __init__ |
| Message-ID | <f8a3fb6e-6878-4aec-9958-5394580ec0e4@googlegroups.com> |
Hi, When running below code, I get error saying:
instance attribute "a" defined outside __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
11
9
why not serially?
9
11
10
[toc] | [next] | [standalone]
| From | John Gordon <gordon@panix.com> |
|---|---|
| Date | 2015-04-01 21:37 +0000 |
| Message-ID | <mfhoel$961$1@reader1.panix.com> |
| In reply to | #88432 |
In <f8a3fb6e-6878-4aec-9958-5394580ec0e4@googlegroups.com> Rio <inkprs@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 > 11 > 9 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@panix.com watch 'House', or a real serial killer to watch 'Dexter'.
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web