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


Groups > comp.lang.python > #68165

Closure/method definition question for Python 2.7

From "Brunick, Gerard:(Constellation)" <Gerard.Brunick@constellation.com>
Subject Closure/method definition question for Python 2.7
Date 2014-03-10 17:27 +0000
Newsgroups comp.lang.python
Message-ID <mailman.8014.1394472539.18130.python-list@python.org> (permalink)

Show all headers | View raw


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.  For example, 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 the point 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

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


Thread

Closure/method definition question for Python 2.7 "Brunick, Gerard:(Constellation)" <Gerard.Brunick@constellation.com> - 2014-03-10 17:27 +0000
  Re: Closure/method definition question for Python 2.7 Marko Rauhamaa <marko@pacujo.net> - 2014-03-10 19:36 +0200
    Re: Closure/method definition question for Python 2.7 Neil Cerutti <neilc@norwich.edu> - 2014-03-11 13:20 +0000

csiph-web