Reputation: 1
I am very new to the python programming so i am not getting what is my error about. so kindly help me to correct this code.
I tried to find out whats wrong but as a new programmer i am not getting
class students:
def __init(self,name,age):
self.name = name
self.age = age
def myfunc(self):
print("Hello i am " + self.name)
p1 = students("Sumit", 28)
p1.myfunc()
It shouldn't give error but it showing error that objects cannot pass something like that. i am not sure what is wrong
Upvotes: 0
Views: 32
Reputation: 57
You are missing double underscores after the init function. It should be like below
class students:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello i am " + self.name)
p1 = students("Sumit", 28)
p1.myfunc()
It's called the magic methods. Python provide this methods to use it as the operator overloading.
Upvotes: 0
Reputation: 2633
Your constructor (__init__
) should have two uderscores on each side:
class students:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello i am " + self.name)
p1 = students("Sumit", 28)
p1.myfunc()
Many python 'internals' follow this practice of being surrounded by two underscores on each side. For example, you can access the variables in a certain class or namespace with the __dict__
keyword.
print(p1.__dict__) # Will print {'name': "Sumit", 'age': 28}
Upvotes: 2