Methods with the same name in one class in Python

前端 未结 9 1662
执笔经年
执笔经年 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:56

    Short answer: you can't (see this previous discussion). Typically you'd use something like (you could add more type checking and reorder):

    def my_method(self,parameter_A, parameter_B=None):
      if isinstance(parameter_B, int):
        print parameter_A * parameter_B
      else:
        print parameter_A
        if parameter_B is not None:
          print parameter_B
    

提交回复
热议问题