Python Class - How do I create a class that accepts undefined number of arguments?

467 Views Asked by At

Im a beginner. For the sake of learning, I have to write a class in python which accepts at most 3 different arguments (a,b,c): something like

 class random(object):

     def __init__(self,a,b,c):
          blah blah blah

How do I make it so that:

  • if no argument is entered, it does one thing.

    for example:

    "test=random()", in this case assume a=b=c=0

  • if one argument is entered, it does another thing.

    for example:

    "test=random(2)", in this case a=2 ,b=c=0, 
     and then run some case specific codes/instrutctions
    
  • and etc

something like how with the builtin function/class "range", where you can use

range(9) range(3,9) range(3,9,2)

if you know what I mean.

thanks

1

There are 1 best solutions below

0
On

It looks like you're asking about Default Argument Values.

When defining a function or method, one way to make parameters optional is to give them default values:

 def __init__(self, a=0, b=0, c=0):

Now, if I call your function (or, in the case of an __init__ function, construct an instance of your class) with no arguments, a, b, and c will all be 0. If I pass 1 argument, b and c will be 0. And so on.

See Arbitrary Argument Lists for another way to do something similar.


The way range works is a little funky, because the first argument has a different meaning if there's only 1 argument vs. 2 or more. There are a handful of other builtins like this, but it's not a good idea for you to emulate them; these are basically only there for backward compatibility reasons (to the days when Python didn't have keywords).

To make things more fun, because 0 is a perfectly valid value for start or stop, and so is even None, you have to construct some special value that nobody could reasonably pass you. (That part, you may actually need to emulate some day.) So, it looks something like this:

class range(object):
    _sentinel = object()
    def __init__(self, start_or_stop, stop=range._sentinel, step=None):
        if stop is range._sentinel:
            start, stop = None, start_or_stop
        else:
            start = start_or_stop
        # Now you can use start, stop, step