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