Closure/method definition question for Python 2.7
Neil Cerutti
neilc at norwich.edu
Tue Mar 11 09:20:35 EDT 2014
On 2014-03-10, Marko Rauhamaa <marko at pacujo.net> wrote:
> "Brunick, Gerard:(Constellation)" <Gerard.Brunick at constellation.com>:
>
>> class Test(object):
>> x = 10
>>
>> def __init__(self):
>> self.y = x
>>
>> t = Test()
>> ---
>>
>> raises
>>
>> NameError: global name 'x' is not defined.
>
> In the snippet, x is neither local to __init__() nor global to
> the module. It is in the class scope. You can refer to it in
> one of two ways:
>
> Test.x
>
> or:
>
> self.x
The latter will work only to read the class variable. If you
assign to self.x you'll create a new instance variable that hides
the class variable.
--
Neil Cerutti
More information about the Python-list
mailing list