Methods with the same name in one class in Python

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

    You probably want a pattern similar to the following: Note that adding '_' to the beginning of a method name is convention for marking a private method.

    class MyClass:
        """"""
    
        #----------------------------------------------------------------------
        def __init__(self):
            """Constructor"""
        def my_method(self,parameter_A_that_Must_Be_String, param2=None):
            if type(param2) == str:
                return self._my_method_extra_string_version(parameter_A_that_Must_Be_String, param2)
            elif type(param2) == int:
                return self._my_method_extra_int_version(parameter_A_that_Must_Be_String, param2)
            else:
                pass # use the default behavior in this function
            print parameter_A_that_Must_Be_String
    
        def _my_method_extra_string_version(self,parameter_A_that_Must_Be_String, parameter_B_that_Must_Be_String):
            print parameter_A_that_Must_Be_String
            print parameter_B_that_Must_Be_String
    
        def _my_method_extra_int_version(self,parameter_A_that_Must_Be_String, parameter_A_that_Must_Be_Int):
            print parameter_A_that_Must_Be_String * parameter_A_that_Must_Be_Int
    

提交回复
热议问题