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


Groups > comp.lang.python > #68169 > unrolled thread

Re: Closure/method definition question (delete 'for Python 2.7')

Started byTerry Reedy <tjreedy@udel.edu>
First post2014-03-10 14:59 -0400
Last post2014-03-10 14:59 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Closure/method definition question (delete 'for Python 2.7') Terry Reedy <tjreedy@udel.edu> - 2014-03-10 14:59 -0400

#68169 — Re: Closure/method definition question (delete 'for Python 2.7')

FromTerry Reedy <tjreedy@udel.edu>
Date2014-03-10 14:59 -0400
SubjectRe: Closure/method definition question (delete 'for Python 2.7')
Message-ID<mailman.8016.1394477980.18130.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web