Search code examples
pythonnamed-parametersdefault-parameters

Default parameter value in this __init__() method's definition?


I am looking at some python code to control a camera and having some trouble understanding it due to being new at python. I see that the src parameter is set to 0. Does this mean that if a src is not given 0 will be used otherwise the given src will be used?

class WebcamVideoStream:

    def __init__(self, src=0):
        # initialize the video camera stream and read the first frame
        # from the stream
        self.stream = cv2.VideoCapture(src)

so if I do something like this

vs = WebcamVideoStream(3)

then the src will be 3? and if I do this

vs = WebcamVideoStream()

then src will be 0?


Solution

  • Quick answer is - yes.

    If you run:

    vs = WebcamVideoStream(3)
    

    src equals to 3

    if you run:

    vs = WebcamVideoStream()
    

    src equals to 0(default value).

    As an additional Python's feature, Python supports *args and **kwargs for cases when you're not sure how much and which arguments will be used in your method(it's very general explanation, but I hope it's clear).

    Some example of using **kwargs I've posted here: http://codepad.org/E7m3PnVr

    P.S.

    1) use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function.

    2) **kwargs allows you to handle named arguments that you have not defined in advance