Methods with the same name in one class in python?

user278618 picture user278618 · Feb 22, 2011 · Viewed 86.6k times · Source

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

What I must to change in this class:

class MyClass:
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
    def my_method(self,parameter_A_that_Must_Be_String):
        print parameter_A_that_Must_Be_String

    def my_method(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(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

Answer

kefeizhou picture kefeizhou · Feb 22, 2011

You can have a function that takes in 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