I am trying to create an object and I'm initializing it with 2 fields first (name & number). However each time I run the program I'm given this error:
TypeError: __init__() missing 1 required positional argument: 'number'
The __init__
method in the class looks like this:
def __init__(self, name, number):
self.__name__ = name
self.__number__ = number
The code where I try to create the object is this:
employee1 = ProductionWorker(Employee)
name = input("Enter employee name:")
number = input("Enter employee number:")
employee1.__init__(name, number)
Does anyone know why I may be getting this error?
CodePudding user response:
Do:
name = input("Enter employee name:")
number = input("Enter employee number:")
employee1 = ProductionWorker(name, number)
You do not generally need to call __init__
explicitly; it's invoked by the ProductionWorker(...)
expression, which passes its arguments to self.__init__
as part of initialization.
You do not need to restate when constructing a new object that Employee
is the parent class; that only needs to be said when the class is defined.
CodePudding user response:
You are using the class as a parameter.
Then, init
is always automatically called on creation. This how it might work as You want (using the show method to validate):
class Employee:
def __init__(self, name, number):
self.__name__ = name
self.__number__ = number
def show(self):
print(self.__name__)
print(self.__number__)
name = input("Enter employee name:")
number = input("Enter employee number:")
employee1 = Employee(name,number)
employee1.show()