简体   繁体   中英

Function definition in Python

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)

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)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM