[Python-Dev] decorators (not transformations) on functions vsclasses

Jewett, Jim J jim.jewett at eds.com
Fri Mar 26 13:52:10 EST 2004


Regarding decorator attributes vs tranformations, I wrote:
>>     def bar():
>>         pass
>>     bar.x = 27
 
>> is not so useful.  
 
>> There is no intermediate "self" scope between function locals 
>> and global, so bar itself can't see x.

Robert Brewer:

> True, but you can also write:

	>>> def bar():
	... 	bar.x = 4
	... 	
	>>> bar()
	>>> bar.x
	4

> ...so bar itself can "see x", 

The x it sees is tied to the name rather than the object.

>>> def f():
...     print f.x
>>> f.x = 5
>>> g=f
>>> f()
5
>>> del f
>>> g()

Traceback (most recent call last):
  File "<pyshell#174>", line 1, in -toplevel-
    g()
  File "<pyshell#169>", line 2, in f
    print f.x
NameError: global name 'f' is not defined

The self namesapce means that you can tie an attribute
directly to a class object (rather than to its name).

>>> class C:
    def printx(self):
        print self.x
>>> D=C
>>> C.x = 6
>>> del C
>>> d=D()
>>> d.printx()
6



More information about the Python-Dev mailing list