Give a reference to a python instance attribute at class definition

Posted by Guenther Jehle on Stack Overflow See other posts from Stack Overflow or by Guenther Jehle
Published on 2010-06-10T17:16:55Z Indexed on 2010/06/10 17:22 UTC
Read the original article Hit count: 270

Filed under:
|
|
|

I have a class with attributes which have a reference to another attribute of this class. See class Device, value1 and value2 holding a reference to interface:

class Interface(object):
    def __init__(self):
        self.port=None

class Value(object):
    def __init__(self, interface, name):
        self.interface=interface
        self.name=name

    def get(self):
        return "Getting Value \"%s\" with interface \"%s\""%(self.name, self.interface.port)

class Device(object):
    interface=Interface()
    value1=Value(interface, name="value1")
    value2=Value(interface, name="value2")

    def __init__(self, port):
        self.interface.port=port

if __name__=="__main__":
    d1=Device("Foo")
    print d1.value1.get() # >>> Getting Value "value1" with interface "Foo"
    d2=Device("Bar")
    print d2.value1.get() # >>> Getting Value "value1" with interface "Bar"
    print d1.value1.get() # >>> Getting Value "value1" with interface "Bar"

The last print is wrong, cause d1 should have the interface "Foo". I know whats going wrong: The line interface=Interface() line is executed, when the class definition is parsed (once). So every Device class has the same instance of interface.

I could change the Device class to:

class Device(object):
    interface=Interface()
    value1=Value(interface, name="value1")
    value2=Value(interface, name="value2")

    def __init__(self, port):
        self.interface=Interface()
        self.interface.port=port

So this is also not working: The values still have the reference to the original interface instance and the self.interface is just another instance...

The output now is:

>>> Getting Value "value1" with interface "None"
>>> Getting Value "value1" with interface "None"
>>> Getting Value "value1" with interface "None"

So how could I solve this the pythonic way? I could setup a function in the Device class to look for attributes with type Value and reassign them the new interface. Isn't this a common problem with a typical solution for it?

Thanks!

© Stack Overflow or respective owner

Related posts about python

Related posts about class