Question
I am new to Python. I was trying to define and run a simple function in a class.
Can anybody please tell me what's wrong in my code:
class A :
def m1(name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
>>> a = A()
>>> a.m1('X',12,'XXXX')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
a.m1('X',12,'XXXX')
I am getting below error
TypeError: m1() takes exactly 3 positional arguments (4 given)
Solution
Instance methods take instance as first argument:
class A :
def m1(self, name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
You can also use @staticmethod decorator to create static function:
class A :
@staticmethod
def m1(name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
OTHER TIPS
The first parameter is always the object itself.
class A :
def m1(self, name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
By convention, methods in a class instance receive an object reference as the 1st argument, named self
.
>>> class A:
... def m1(self,name,age,address):
... print('Name -->',name)
... print('Age -->',age)
... print('Address -->',address)
...
>>> a=A()
>>> a.m1('X',12,'XXXX')
('Name -->', 'X')
('Age -->', 12)
('Address -->', 'XXXX')
>>>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow