[Python] Access `self` in classmethod when instance (self) calls classmethod

Discussão em 'Python' iniciado por Stack, Fevereiro 5, 2025.

  1. Stack

    Stack Membro Participativo

    Is it possible to access the object instance in a Python @classmethod annotated function when the call occurs via the instance itself rather than the class?

    class Foo(object):
    def __init__(self, text):
    self.text = text

    @classmethod
    def bar(cls):
    return None

    print(Foo.bar())

    foo = Foo('foo')
    # If possible, I'd like to return "foo"
    print(foo.bar())



    I'm working around limitations of a library which calls a class method via the instance (rather than the class) and was hoping I could somehow workaround the fact that I can only access the class in bar(cls) (I'd to access the instance to access .text). I don't think that's possible, but I thought I'd ask (I couldn't unearth something on the internet either for such a niche request).

    Continue reading...

Compartilhe esta Página