0

Some code I have a problem with:

# a connector
class conn():
    def __init__(self, name):
        self.name = name

# a device base class
class imper_dev():
    names = []
    conns = {}
    def __init__(self):
        for name in self.names:
            self.conns[name] = conn(name)

# a real device          
class dev(imper_dev):   
    names = ['a']       

# some instances of it               
d1 = dev()              
d2 = dev()              

>>> d1.conns['a']
<__main__.conn object at 0x7fd68871c630>      
>>> d2.conns['a'] 
<__main__.conn object at 0x7fd68871c630>

I am a little surprised by this behavior. My intention is to create instances of dev() with independent connectors. Why have both instances d1 and d2 the same reference for conns['a']?

hinerk
  • 43
  • 1
  • 5
  • Have a look at [static variables in a class](http://stackoverflow.com/questions/68645/static-class-variables-in-python). – Reti43 Jan 16 '16 at 18:25

1 Answers1

0

conns is a class variable which means that variable is shared between all instances of the dev class. Note that d1 and d2 are actually different objects, it's only conns and names that are shared here.

>>> d1
<__main__.dev instance at 0x7fb757329050>
>>> d2
<__main__.dev instance at 0x7fb7573290e0>
shuttle87
  • 15,466
  • 11
  • 77
  • 106