Methods with the same name in one class in Python

前端 未结 9 1646
执笔经年
执笔经年 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
    
    0 讨论(0)
  • 2021-01-30 02:59

    You can have a function that takes in a variable number of arguments.

    def my_method(*args, **kwds):
        # Do something
    
    # When you call the method
    my_method(a1, a2, k1=a3, k2=a4)
    
    # You get:
    args = (a1, a2)
    kwds = {'k1':a3, 'k2':a4}
    

    So you can modify your function as follows:

    def my_method(*args):
        if len(args) == 1 and isinstance(args[0], str):
            # Case 1
        elif len(args) == 2 and isinstance(args[1], int):
            # Case 2
        elif len(args) == 2 and isinstance(args[1], str):
            # Case 3
    
    0 讨论(0)
  • 2021-01-30 03:06

    You can't. There are not overloads or multimethods or similar things. One name refers to one thing. As far as the language is concerned anyway, you can always emulate them yourself... You could check types with isinstance (but please do it properly - e.g. in Python 2, use basestring to detect both strings and unicode), but it's ugly, generally discouraged and rarely useful. If the methods do different things, give them different names. Consider polymorphism as well.

    0 讨论(0)
提交回复
热议问题