Mike Williamson
Mike Williamson

Reputation: 3238

Does Python allow for multiple input parameters to a class method?

I can not seem to find an answer for this question on the interwebs. In Python, am I able to do something like this:

class MyClass(object):
    """It's my class, yo!"""
    def __init__(self, string_of_interest_1):
        self.string1 = string_of_interest_1
        self.string2 = None
        self.int1 = None
    def __init__(self, string_of_interest_1, string_of_interest2):
        self.string1 = string_of_interest_1
        self.string2 = string_of_interest_2
        self.int1 = None
    def __init__(self, int_of_interest_1):
        self.string1 = None
        self.string2 = None
        self.int1 = int_of_interest_1

I call this "method-overloading", but it seems the standard overloading is when I have some variables that I assign a default value to within the call itself. (E.g., def __init__(self, string_of_interest_1, string_of_interest_2 = None)) While this tiny example does not demonstrate it, I would like the potential to have truly different methods depending upon how many, and what type, of parameters are passed to it.

Thanks!

Upvotes: 1

Views: 2714

Answers (3)

Alexander Zh
Alexander Zh

Reputation: 111

In python there is no overloading of functions or methods, but there is a change - *args and **kwargs. Example:

>>def test(*args, **kwargs):
>>    print args # list of positional parametrs
>>    print kwargs # dict of named parametrs

>>test(1, 2, test_param='t')
[1, 2]
{test_param: 't'}

Upvotes: 2

Juan David
Juan David

Reputation: 2797

You can take all the arguments that you want even when your function doesn't know the number. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args. What *args allows you to do is take in more arguments than the normal of formal arguments that you previously defined. Check this thread to see an example of how you can do it

*args and **kwargs?

Upvotes: 1

Neel
Neel

Reputation: 21297

All variable in Python is object even int is also a object.

Method overriding used in C, JAVA etc..

Python has magic variable * and **. * is used for position argument, and ** used as keyword argument

try this

def test_method(*args, **kwargs):
    print args
    print kwargs

Call this function with different different argument and you will get idea about these magic methods.

Upvotes: 1

Related Questions