[Tutor] Object attributes surviving deletion

wesley chun wescpy at gmail.com
Fri Jun 27 02:29:02 CEST 2008


> If I 'overwrite' a class variable
> with an instance one (as I did originally), is the class variable
> recoverable? Will objects created later have the class or the instance
> variable?


yes, but you need to access it with the class name: Grammars.database

the other (uglier) alternative is to remove the instance attribute
from the namespace, and then you are able to get access to it again.
in other words, when you created the (dynamic) instance attribute you
"shadowed" access to the class attribute. but by doing "del
self.database", you've removed that shadow so that self.database is
pointing at the class one again:

>>> class C(object):
...  data = 1
...
>>>
>>> c = C()
>>>
>>> c.data    # access class attr
1
>>> c.data += 1    # created new instance attr
>>> c.data    # look at new instance attr
2
>>> C.data    # access class attr
1
>>> del c.data    # remove new instance attr
>>> c.data    # access class attr again
1

granted, that it's "weird" to see code like the last 2 stmts adjacent
to each other.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list