MMC
MMC

Reputation: 175

TypeError: __init__() takes 3 positional arguments but 4 were given

These are the codes for my classes:

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

class Salary:
    def jump(self, name, salary):
        print(self.name, self.salary)


class Male(Salary, Employee):
    def __init__(self, name, gender, occupation):
        super(Male, self).__init__(name, gender, occupation)
        self.occupation = occupation

# Separate from all classes (list of instantiated objects)
employee1 = Male("Jim", "male", "technician")
print(Male.name)

When I use the last two lines of the code after creating all my classes, a TypeError: __init__() takes 3 positional arguments but 4 were given error occurs referencing the super(Male, self).... and employee1 = Male(... lines.

Upvotes: 6

Views: 127918

Answers (3)

cdiaza
cdiaza

Reputation: 31

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

class Salary:
    def __init__(self,name,gender):
        self.name=name
        self.gender=gender
    def jump(self):
        print(self.name,self.salary)

class Male(Salary,Employee):
    def __init__(self,name,gender,occupation):
        self.occupation=occupation
        super().__init__(name,gender)


employee1 = Male("Jim","male","technician")
print(employee1.name)

""" You were writing the occupation parameter in the super, but super calls to the parent class and your parent class does not have occupation parameter. The occupation belongs only to the Class Male."""

Upvotes: 3

Eyssant
Eyssant

Reputation: 11

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

class Salary:
  def __init__(self, name, gender):
    self.name = name
    self.gender = gender   
  def jump(self):
    print(self.name, self.salary)

class Male(Salary, Employee):
    def __init__(self, name, gender, occupation):
      self.occupation = occupation
      Employee.__init__(self, name, gender)
      Salary.__init__(self, name, gender)

employee1 = Male("Jim", "male", "technician")
print(employee1.name)

Python - Inheritance

To access all the methods and properties of base class Employee, super() function is used in derived class Male. Syntax for using super function is shown in example. Along with this, use print(employee1.name) instead of print(Male.name).

Upvotes: 0

chngzm
chngzm

Reputation: 628

Under Pet you have:

def __init__(self, name, color):
    self.name = name
    self.color = color

Under Dog you have:

def __init__(self, name, color, owner):
    super(Dog, self).__init__(name, color, owner)

Under Dog there's an extra owner positional argument given, which leads to this error. On a side note, I think super().__init__(name, color) works just as well too in Python 3

Upvotes: 9

Related Questions