Python bug with dictionary

Ben Finney bignose-hates-spam at and-zip-does-too.com.au
Tue Jul 22 01:27:35 EDT 2003


On Mon, 21 Jul 2003 20:27:32 -0400, none wrote:
> class Dict:
>     items = {}
>     name = ""

These attributes belong to the class, and are not distinct between
instances.  (For the same reason, all the functions you define in the
class become methods, shared between all instances.)

If you want each instance to have attributes distinct from other
instances, set them during the instance's initialisation:

=====
>>> class Foo( object ):
...     def __init__( self, name = None ):
...         self.items = {}
...         self.name = name
...     def addItem( self, item ):
...         self.items[ item.name ] = item
...
>>> class Bar( object ):
...     def __init__( self, name = None ):
...         self.name = name
...
>>> bar1 = Bar( "bar1" )
>>> bar2 = Bar( "bar2" )
>>> bar3 = Bar( "bar3" )
>>> bar4 = Bar( "bar4" )
>>>
>>> foo1 = Foo( "foo1" )
>>> foo2 = Foo( "foo2" )
>>>
>>> foo1.addItem( bar1 )
>>> foo1.addItem( bar2 )
>>>
>>> foo2.addItem( bar3 )
>>> foo2.addItem( bar4 )
>>>
>>> foo1.name
'foo1'
>>> foo1.items.keys()
['bar1', 'bar2']
>>>
>>> foo2.name
'foo2'
>>> foo2.items.keys()
['bar3', 'bar4']
>>>
=====

I've also changed two other things: don't name objects (of any kind)
after reserved words like "dict", you'll just lead to confusion.  Don't
bother with redundant getBlah() and setBlah() methods; just access the
attributes directly, using __getitem__() and __setitem__() in the few
cases where you actually need to intervene.

-- 
 \     "[The RIAA] have the patience to keep stomping. They're playing |
  `\      whack-a-mole with an infinite supply of tokens."  -- kennon, |
_o__)                                             http://kuro5hin.org/ |
http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B




More information about the Python-list mailing list