In PHP one can create a reference variable, so that two named variables can look at the same value:
$a = 1;
$b =& $a;
echo $a; // 1
echo $b; // 1
$b = 2;
echo $a; // 2
I’m looking to achieve something similar in Python. Specifically, I want to create a reference to an object’s property, eg:
class Foo(object):
@property
def bar(self): return some_calculated_value
foo_instance = Foo()
ref = foo_instance.bar
# so that 'ref' is referencing the bar property on foo, calculated when used.
Is this possible?
There is some more magic that can be done in Python (not that I would recommend it and it will require digging on your part ;-), but using a closure may be sufficient for your needs:
Edit, for those wanting “update support”, it’s all about the closures:
Without stepping outside the bounds of normally (for me 🙂 accepted Python, this could also be written to return an object with forwarding/proxy property, imagine:
Some interesting links: