[Python-Dev] function attributes as "true" class attributes & reclamation error

Guido van Rossum guido@python.org
Sat, 06 Jan 2001 17:05:23 -0500


> You know, I thought of something (which was probably already obvious to the
> rest of you) while perusing Barry's patch.  Attaching function attributes to
> unbound methods could really function like C++ static data members.  You'd
> have to write accessor functions to make setting the attributes look clean,
> but that wouldn't be all bad.  Precisely because you couldn't modify them
> through the bound method, there's be no chance you could make the mistake of
> modifying them that way and having them transmogrify into instance
> attributes.
> 
> Here's a quick example:
> 
>     class C:
>       def __init__(self):
> 	self.just_resting()
>       __init__.howmany = 0
> 
>       def __del__(self):
> 	self.hes_dead()
> 
>       def hes_dead(self):
> 	C.__init__.howmany -= 1
> 
>       def just_resting(self):
> 	C.__init__.howmany += 1
> 
>       def howmany(self):
> 	return C.__init__.howmany
> 
>     def howmany():
> 	return C.__init__.howmany
> 
>     c = C()
>     print c.howmany()
>     d = C()
>     print d.howmany()
>     del c
>     print d.howmany()

Skip, I don't find this better than the existing solution, which uses
C._howmany instead of C.__init__.howmany.

True, you can access it as self._howmany and if you assign to
self._howmany you'd transform it into an instance attribute -- but
that falls in the "then don't do that" category.

--Guido van Rossum (home page: http://www.python.org/~guido/)