Superclass static method name from subclass
Cameron Simpson
cs at cskk.id.au
Fri Nov 11 17:17:26 EST 2022
On 11Nov2022 10:21, Ian Pilcher <arequipeno at gmail.com> wrote:
>Is it possible to access the name of a superclass static method, when
>defining a subclass attribute, without specifically naming the super-
>class?
>
>Contrived example:
>
> class SuperClass(object):
> @staticmethod
> def foo():
> pass
>
> class SubClass(SuperClass):
> bar = SuperClass.foo
> ^^^^^^^^^^
>
>Is there a way to do this without specifically naming 'SuperClass'?
I think not.
All the posts so far run from inside methods, which execute after you've
got an instance of `SubClass`.
However, during the class definition the code under `class SubClass` is
running in a standalone namespace - not even inside a completed class.
When that code finished, that namespace is used to create the class
definition.
So you have no access to the `SuperClass` part of `class
SubClass(SuperClass):` in the class definition execution.
Generally it is better to name where something like this comes from
anyway, most of the time.
However, if you really want to plain "inherit" the class attribute
(which I can imagine valid use cases for), maybe write a property?
@property
def bar(self):
return super().foo
That would still require an instance to make use of it, so you can't
write explicitly `SubClass.bar`.
Possibly a metaclass would let you write a "class property", or to
define `bar` as a class attribute directly.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Python-list
mailing list