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

Asked By: Farhan Hermansyah

||

Answers:

Your _init_ function in your class is not the main initializer. To make it that, rename it to __init__.

Answered By: llamaking136

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()
Answered By: anjandash
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.