Search code examples
pythonclassooppositional-argument

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


I was making a python class in which it has an employee's name, salary, and the number of leaves as attributes and was trying to show the final salary of an employee deducting the salary for the days he/she has not come but it is showing an error. The error is:

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

I had written the code:

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()

Solution

  • You should call the method on the instance not the class object.

    john_smith.f_salary()
    john_smith.display()
    

    Because the self parameter is a reference to the class instance which called the method in the first place.