Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #88433

Re: instance attribute "a" defined outside __init__

From John Gordon <gordon@panix.com>
Newsgroups comp.lang.python
Subject Re: instance attribute "a" defined outside __init__
Date 2015-04-01 21:37 +0000
Organization PANIX Public Access Internet and UNIX, NYC
Message-ID <mfhoel$961$1@reader1.panix.com> (permalink)
References <f8a3fb6e-6878-4aec-9958-5394580ec0e4@googlegroups.com>

Show all headers | View raw


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'.

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

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

csiph-web