Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #68169
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Subject | Re: Closure/method definition question (delete 'for Python 2.7') |
| Date | 2014-03-10 14:59 -0400 |
| References | <71E0ECF7BE49E84CBD47914C9E19FFED2793AD54@exchm-omf-22.exelonds.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.8016.1394477980.18130.python-list@python.org> (permalink) |
On 3/10/2014 1:27 PM, Brunick, Gerard:(Constellation) wrote: > 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. In Python, period. > I would assume that when __init__ is being defined, > it is just a regular old function Right. It is an attribute of the class much like other object. This is more obvious and more consistent in Python 3. In Python 3, these two code snippets have the same effect. class C: def f(self): return self.a g = C.f # in2.x, C.f.im_func def g(self): return self.a class C: pass C.f = g This is possible because functions are only loosely coupled to the class they are defined in, through the public attribute mechanism. This is handy for testing. There is no private namespace tie. As long as self.a exists, g could function even if the class C object were deleted or inaccessible. A function that accesses module globals *does* have a private namespace tie to the module it is defined in (lexical scoping), and this must be accounted for when testing or otherwise using it in another module -- perhaps by altering the original module. > and x is a variable in an outer scope, Non-global 'outer scope' is peculiar to lexically nested functions. Any nonlocal access ties a function to its outer function through private internal references. -- Terry Jan Reedy
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Closure/method definition question (delete 'for Python 2.7') Terry Reedy <tjreedy@udel.edu> - 2014-03-10 14:59 -0400
csiph-web