2

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)

3 Answers 3

18

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)
Sign up to request clarification or add additional context in comments.

Comments

4

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)

Comments

4

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

1 Comment

that's not a class method, that's instance method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.