Alias for an attribute defined in a superclass

Steven D'Aprano steve+comp.lang.python at
Fri Apr 1 02:14:41 CEST 2011

On Fri, 01 Apr 2011 09:14:03 +1100, Ben Finney wrote:

> Howdy all,
> I want to inherit from a class, and define aliases for many of its
> attributes. 

Are these aliases of arbitrary aliases, or only of methods, as in your 
example below?

> How can I refer to “the attribute that will be available by
> name ‘spam’ once this class is defined”?

You might be able to use the descriptor protocol to do something like 
that, but otherwise I don't think you can. However, I note that your 
example isn't *quite* how you describe it above.

>     class Foo(object):
>         def spam(self):
>             pass
>         def eggs(self):
>             pass
>     class Bar(Foo):
>         beans = Foo.spam
>         mash = Foo.eggs

This assigns the name Bar.beans to the method object Foo.spam. If you now 
rebind the name Foo.spam to something else, Bar.beans will not likewise 
change, but will continue to refer to the original. This is contrary to 
your earlier description, where Bar.beans should also change.

This is no different from the usual Python namespace behaviour:

x = 42
y = x

y is an alias to x, until you rebind x. For variables, you can't change 
the behaviour; for attributes of a class, you may be able to write a 
descriptor to do something along those lines.

> Is that the right way to do it? Will that leave me open to “unbound
> method” or “is not an instance of ‘Bar’” or other problems when using
> ‘Bar.beans’?

I don't believe so. So long as you don't rebind the "alias" or the 
original, you should be fine.


More information about the Python-list mailing list