Methods with the same name in one class in Python

前端 未结 9 1665
执笔经年
执笔经年 2021-01-30 02:18

How can I declare a few methods with the same name, but with different numbers of parameters or different types in one class?

What must I change in the following class?

9条回答
  •  佛祖请我去吃肉
    2021-01-30 02:43

    This cannot work. No matter how many arguments you have, the name m will be overriden with the second m method.

    class C:
        def m(self):
            print('m first')
        def m(self, x):
            print(f'm second {x}')
    
    
    ci=C();
    #ci.m() # will not work TypeError: m() missing 1 required positional argument: 'x'
    ci.m(1) # works
    

    The output will simple be:

    m second 1
    

提交回复
热议问题