object references

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Mar 27 11:31:04 EST 2006


On Sat, 25 Mar 2006 21:33:24 -0800, DrConti wrote:

> Dear Python developer community,
> I'm quite new to Python, so perhaps my question is well known and the
> answer too.
> 
> I need a variable alias ( what in other languages you would call  "a
> pointer" (c) or "a reference" (perl))

Others have given you reasons why you can't do this, or shouldn't do this.
In general, I agree with them -- change your algorithm so you don't
need indirect references. 

But if you can't get away from it, here is another work-around that might
help:



> class ObjectClass:
> 	""" Test primary Key assignment """
> 
> if __name__ == "__main__":
> 
> 	ObjectClassInstantiated=ObjectClass()
> 	ObjectClassInstantiated.AnAttribute='First PK Elem'
> 	ObjectClassInstantiated.AnotherOne='Second PK Elem'
> 	ObjectClassInstantiated.Identifier=[]
> 	ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute)
> 	ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnotherOne)
> 	print ObjectClassInstantiated.Identifier
> 	ObjectClassInstantiated.AnAttribute='First PK Elem Changed'
> 	print ObjectClassInstantiated.Identifier


# helper class
class Indirect:
    def __init__(self, value):
        self.value = value
    def mutate(self, newvalue):
        self.value = newvalue
    def __eq__(self, other):
        return self.value == other
    def __repr__(self):
        return "-> %r" % self.value

instance = ObjectClass()
instance.attribute = Indirect('First PK Elem')
instance.another_attribute = Indirect('Second PK Elem')
instance.identifier = [instance.attribute, instance.another_attribute]

print instance.identifier
instance.attribute.mutate('First PK Elem Changed')
print instance.identifier

which prints 

[-> 'First PK Elem', -> 'Second PK Elem']
[-> 'First PK Elem Changed', -> 'Second PK Elem']

as requested.


-- 
Steven.




More information about the Python-list mailing list