1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Why does Python pass an instance to a class attribute that is a function?

Discussão em 'Python' iniciado por Stack, Abril 1, 2025.

  1. Stack

    Stack Membro Participativo

    I define a class attribute and give it a function. When I call this function, the instance is passed on as the first argument (as if it's an instance function call with a self). I would not expect an instance to care that the attribute fn is a function, let alone for it to pass itself as an argument. Why does it do that?

    class BStatic:
    fn = None
    @staticmethod
    def static_fn(*args, **kwargs):
    print(args, kwargs)

    BStatic.fn = BStatic.static_fn

    bs = BStatic()

    bs.fn()
    # (<__main__.BStatic object at 0x0000022D63214590>,) {}

    BStatic.fn()
    # () {}


    In another example, I assigned a class attribute to a function defined on a module. When I call this function on an instance of a class, the instance is again passed as the first argument.

    class B:
    fn = None
    def instance_fn(self, *args, **kwargs):
    print(self, args, kwargs)

    def fn(*args, **kwargs):
    print(args, kwargs)

    B.fn = fn

    B.fn()
    # () {}

    b = B()

    b.fn()
    # (<__main__.B object at 0x0000022D643D23F0>,) {}


    This is not the case if I assign the class attribute on an instance.

    b.fn = fn

    b.fn()
    # () {}

    Continue reading...

Compartilhe esta Página