Typerror using class in Python
Question:
I am learning about classes and objects in Python, but when I run this code the output is an error. Can anyone show me how to fix it?
class Person :
def _init_ (self,name,age) :
self.name = name
self.age = age
def myfunction(self) :
print("Hello My Name Is" + self.name)
p1 = Person("John",36)
p1.myfunction()
Here’s the error output:
Traceback (most recent call last): File "F:IPBPENUGASANSEMESTER
2STRAKDATPenugasanPertemuan 3Materi 3.py", line 16, in
p1 = Person("John",36) TypeError: Person() takes no arguments
—————— (program exited with code: 1)
Press any key to continue . . . Terminate batch job (Y/N)?
Answers:
Your _init_
function in your class is not the main initializer. To make it that, rename it to __init__
.
Two things:
Your indentation is not set properly.
The __init__
should be with double underscores.
Try this:
class Person:
def __init__(self,name,age) :
self.name = name
self.age = age
def myfunction(self) :
print("Hello My Name Is " + self.name)
p1 = Person("John",36)
p1.myfunction()
I am learning about classes and objects in Python, but when I run this code the output is an error. Can anyone show me how to fix it?
class Person :
def _init_ (self,name,age) :
self.name = name
self.age = age
def myfunction(self) :
print("Hello My Name Is" + self.name)
p1 = Person("John",36)
p1.myfunction()
Here’s the error output:
Traceback (most recent call last): File "F:IPBPENUGASANSEMESTER
2STRAKDATPenugasanPertemuan 3Materi 3.py", line 16, in
p1 = Person("John",36) TypeError: Person() takes no arguments—————— (program exited with code: 1)
Press any key to continue . . . Terminate batch job (Y/N)?
Your _init_
function in your class is not the main initializer. To make it that, rename it to __init__
.
Two things:
Your indentation is not set properly.
The __init__
should be with double underscores.
Try this:
class Person:
def __init__(self,name,age) :
self.name = name
self.age = age
def myfunction(self) :
print("Hello My Name Is " + self.name)
p1 = Person("John",36)
p1.myfunction()