Methods with the same name in one class in Python

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

    I think one very simple example is missing from all the answers, and that is: what to do when the only difference between variations on the method is the number of arguments. The answer still is to use a method with variable number of arguments.

    Say, you start with a method that requires use of two arguments

    def method(int_a, str_b):
        print("Got arguments: '{0}' and '{1}'".format(int_a, str_b)
    

    then you need to add a variant with just the second argument (say, because the integer is redundant), the solution is very simple:

    def _method_2_param(int_a, str_b):
        print("Got arguments: '{0}' and '{1}'".format(int_a, str_b))
    
    def _method_1_param(str_b):
        print("Got argument: '{0}'".format(str_b))
    
    def method(*args, **kwargs):
        if len(args) + len(kwargs) == 2:
            return _method_2_param(args, kwargs)
        elif len(args) + len(kwargs) == 1:
            return _method_1_param(args, kwargs)
        else:
            raise TypeError("Method requires one or two arguments")
    

    The nice thing about this solution is that no matter if the calling code used keyword arguments or positional arguments before, it will still continue to work.

提交回复
热议问题