Alias for an attribute defined in a superclass
Ben Finney
ben+python at benfinney.id.au
Thu Mar 31 20:59:47 EDT 2011
Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:
> On Fri, 01 Apr 2011 09:14:03 +1100, Ben Finney wrote:
>
> > 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?
I'd like to know how to do either, for making API wrapper classes.
> > 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.
Yes, I got the names wrong. The example is accurate to what I'm meaning
to say.
> > 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.
Hmm. I think I can live with that limitation.
> > 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.
Okay, thank you.
--
\ “I am too firm in my consciousness of the marvelous to be ever |
`\ fascinated by the mere supernatural …” —Joseph Conrad, _The |
_o__) Shadow-Line_ |
Ben Finney
More information about the Python-list
mailing list