n88b
n88b

Reputation: 153

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

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:

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

Upvotes: 2

Views: 512

Answers (1)

abarnert
abarnert

Reputation: 365707

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

Upvotes: 4

Related Questions