Create an alias to an attribute on superclass
Chris Angelico
rosuav at gmail.com
Thu Feb 1 13:49:44 EST 2018
On Fri, Feb 2, 2018 at 5:44 AM, Sean DiZazzo <sean.dizazzo at gmail.com> wrote:
> On Thursday, February 1, 2018 at 10:37:32 AM UTC-8, Chris Angelico wrote:
>> On Fri, Feb 2, 2018 at 5:22 AM, Sean DiZazzo <sean.dizazzo at gmail.com> wrote:
>> > Hi!
>> >
>> > I basically just want to create an alias to an attribute on an item's superclass. So that after I create the subclass object, I can access the alias attribute to get the value back.
>> >
>> > <pre>
>> > class Superclass(object):
>> > def __init__(self, value):
>> > """
>> > I want to pass x by reference, so that any time
>> > x on the subclass is updated, so is the alias here
>> > """
>> > self.alias = value
>> >
>> > class Subclass(Superclass):
>> > def __init__(self, x):
>> > self.x = x
>> > Superclass.__init__(self, self.x)
>> >
>> > def __repr__(self):
>> > return "x: %s\nalias: %s" % (self.x, self.alias)
>> >
>> >
>> > if __name__ == "__main__":
>> > foo = Subclass(1)
>> > print foo.alias
>> >
>> > foo.x = 6
>> > # Should return 6 !!!
>> > print foo.alias
>> >
>> > </pre>
>>
>> ISTM the easiest way would be to define a property on the superclass:
>>
>> class Superclass(object):
>> @property
>> def alias(self):
>> return self.x
>>
>> Whatever happens, self.alias will be identical to self.x. Is that what
>> you're after?
>>
>> ChrisA
>
> Yes, but that doesn't seem to work. It looks like there is a way to do it if you make the original value a list (mutable) instead of an integer. I really need to do it with an arbitrary object. Not sure if I can hack the list trick to work in my case though.
>
Can you post your actual code? The alias will be looked up whenever
you ask for it, so it won't be a copy.
ChrisA
More information about the Python-list
mailing list