[Python] Why does calling instance methods through class name need explicit self?

Discussão em 'Python' iniciado por Stack, Maio 29, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to call a method both through an object and through the class itself.

    class Management:
    factory = "Youtube"

    def getSalary(self, signature):
    print("Salary is I don't Know")
    print(f"Salary is {self.salary} \n {signature}")

    # Create an object
    man = Management()

    # Set an attribute dynamically
    man.salary = 30000

    # Call method through object (works fine)
    man.getSalary("thanks")

    # Call method through class (this causes an error)
    Management.getSalary(man)


    When I run this, the first method call via the object works fine:

    Salary is I don't Know
    Salary is 30000
    thanks


    But the second call via the class:

    Management.getSalary(man)


    gives me this error:

    TypeError: getSalary() missing 1 required positional argument: 'signature'


    I thought passing man would be enough, and it would use the salary from the object and print the salary and signature as before.

    I double-checked my indentation, method definition, and attribute assignment. Still the same error.

    Why is Python giving this error when calling the method via the class, and how should I properly pass the arguments in this situation?

    Continue reading...

Compartilhe esta Página