Closure/method definition question for Python 2.7

  • Thread starter Brunick, Gerard:(Constellation)
  • Start date

B

Brunick, Gerard:(Constellation)

The following code:

---
class Test(object):
x = 10

def __init__(self):
self.y = x

t = Test()
---

raises

NameError: global name 'x' is not defined.

in Python 2.7. I don't understand why. I would assume that when __init__ is being defined, it is just a regular old function and x is a variable in an outer scope, so the function __init__ would close over the variable x. Moreover, the variable x is not being modified, so this should be O.K. Forexample, the following is fine (if nonsensical):

---
def outer():
x = 10

def __init__(self):
self.y = x

return __init__

t = outer()
print t
---

Can anyone explain this behavior? It is clear that you could simply use self.x to access the variable x inside of __init__, but this isn't really thepoint of the question.

Thanks in advance,
Gerard

This e-mail and any attachments are confidential, may contain legal,
professional or other privileged information, and are intended solely for the
addressee. If you are not the intended recipient, do not use the information
in this e-mail in any way, delete this e-mail and notify the sender. -EXCIP
 
Ad

Advertisements

M

Marko Rauhamaa

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


Marko
 
Ad

Advertisements

N

Neil Cerutti

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top