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
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:
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
, andc
will all be 0. If I pass 1 argument,b
andc
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 forstart
orstop
, and so is evenNone
, 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: