Python class 显示 "missing 1 required positional argument: 'self'"

Python class showing "missing 1 required positional argument: 'self'"

我正在制作一个 python class,其中包含员工姓名、薪水和休假数作为属性,并试图显示最终薪水员工扣了he/she天的工资还没有来,但是显示错误。错误是:

    TypeError: Employee.f_salary() missing 1 required positional argument: 'self'
      

我写过代码:

class Employee:
    def __init__(self, name, salary, no_of_leaves):
        self.name = name
        self.salary = salary
        self.no_of_leaves = no_of_leaves

    def f_salary(self):
        self.f_salary1 = self.salary - 500 * int(self.no_of_leaves)

    def display(self):
        print(f"Employee's name: {self.name}\nEmployee's monthly salary: 
        {self.salary}\nNo.of leaves that employee has taken: {self.no_of_leaves}")

nol = input("No. of leaves the employee has taken: ")

john_smith = Employee('John Smith', 182500, nol)

Employee.f_salary()
Employee.display()

您应该在实例而不是 class 对象上调用方法。

john_smith.f_salary()
john_smith.display()

因为 self 参数是对首先调用该方法的 class 实例的引用。

问题是您在 class 而不是您创建的对象上调用方法。

Employee.f_salary()
Employee.display()

这可以通过使用对象名称轻松解决。

john_smith.f_salary()
john_smith.display()

不过,如果您使用 class 调用方法,则可以显式传递 self。

class Foo:
    def bar(self):
        # Etc.

some_foo = Foo()

# These are more or less equivalent if we assume no class extends Foo
Foo.bar(some_foo)
some_foo.bar()

实例方法只是 class 属性。 Employee.f_salary 是对需要单个参数的函数的引用。

不过,

john_smith.f_salary 更有趣。因为 function 对象实现了 descriptor protocol,访问作为某物属性的值总是会触发它的 __get__ 方法,因此

Employee.f_salary == Employee.__dict__['f_salary'].__get__(None, Employee)
john_smith.f_salary == Employee.__dict__['f_salary'].__get__(john_smith, Employee)

在第一种情况下,__get__ 只是 returns 函数本身,因此当您尝试调用它时,它仍然需要一个参数作为其 self 参数。

在第二种情况下,__get__ returns method class 的一个实例,它在内部保留两个引用:一个指向 john_smith,以及一个函数本身。

当您尝试调用 method 对象时,它只是获取自己的参数并将它们与 john_smith 一起传递给基础函数。

因此,john_smith.f_salary() returns Employee.f_salary(john_smith) 的值。