On 11Nov2022 10:21, Ian Pilcher <arequip...@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 <c...@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to