Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #2342
| Date | 2011-04-01 11:54 +0200 |
|---|---|
| From | Jean-Michel Pichavant <jeanmichel@sequans.com> |
| Subject | Re: Alias for an attribute defined in a superclass |
| References | <87sju3ndjo.fsf@benfinney.id.au> <787d36b9-e31d-4b61-a14e-770337cfc280@a11g2000pro.googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.68.1301651655.2990.python-list@python.org> (permalink) |
Raymond Hettinger wrote:
> On Mar 31, 3:14 pm, Ben Finney <ben+pyt...@benfinney.id.au> wrote:
>
>> Howdy all,
>>
>> I want to inherit from a class, and define aliases for many of its
>> attributes. How can I refer to “the attribute that will be available by
>> name ‘spam’ once this class is defined”?
>>
>> class Foo(object):
>> def spam(self):
>> pass
>>
>> def eggs(self):
>> pass
>>
>> class Bar(Foo):
>> beans = Foo.spam
>> mash = Foo.eggs
>>
>> Is that the right way to do it?
>>
>
> For methods, that will work just fine. For attributes, you will need
> to make @property accessors that get and set the underlying attribute.
>
>
> Raymond
>
For attributes you could also override __getattribute__ & __setattr__ to
wrap Bar's names into Foo's names.
Could work also for methods, but for methods your current idea is much
more simple.
class Foo(object):
def __init__(self):
self.spam = 'someSpam'
self.eggs = 'fewEggs'
def vanilla(self):
return self.spam
class Bar(Foo):
_map = {
'beans': 'spam',
'mash': 'eggs',
'chocolate': 'vanilla',
}
def __getattribute__(self, attribute):
getSafely = object.__getattribute__
_map = getSafely(self, '_map')
if attribute in _map:
return getSafely(self, _map[attribute])
else:
return getSafely(self, attribute)
Bar().chocolate()
'someSpam'
Bar().mash
'fewEggs'
JM
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Alias for an attribute defined in a superclass Ben Finney <ben+python@benfinney.id.au> - 2011-04-01 09:14 +1100
Re: Alias for an attribute defined in a superclass Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-04-01 00:14 +0000
Re: Alias for an attribute defined in a superclass Ben Finney <ben+python@benfinney.id.au> - 2011-04-01 11:59 +1100
Re: Alias for an attribute defined in a superclass Calvin Spealman <ironfroggy@gmail.com> - 2011-03-31 20:36 -0400
Re: Alias for an attribute defined in a superclass Ben Finney <ben+python@benfinney.id.au> - 2011-04-01 11:57 +1100
Re: Alias for an attribute defined in a superclass Raymond Hettinger <python@rcn.com> - 2011-03-31 19:24 -0700
Re: Alias for an attribute defined in a superclass Jean-Michel Pichavant <jeanmichel@sequans.com> - 2011-04-01 11:54 +0200
csiph-web