Create an alias to an attribute on superclass
Chris Angelico
rosuav at gmail.com
Thu Feb 1 13:36:58 EST 2018
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
More information about the Python-list
mailing list