jxie0755
jxie0755

Reputation: 1742

Class default parameter in python

if I create a class called Car

class Car():
    '''car information summary'''
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer = 0

I learned that self.odometer=0 allowed me creating a new instance without putting a value for odometer. Every new instance will start with an odometer reading at 0.

But what if I want to create an new instance with a specified odometer reading?

car_1 = Car('Audi', 'S4', '2017', 5000)

It won't allow me to do so. What I am trying to do is to use it like a default value for a function: You don't have to give a value because there is a default, but when you do, you can overwrite the default.

And I do understand that I can revise the attribute afterwards, or write a method to change the attribute. But that's not my concern for now.

Is this a wrong idea to have for OOP?

Upvotes: 1

Views: 95

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476547

Python supports the concept of parameters with a default value. You can write a parameter, and give it a default value if it is not specified. In this case it looks like:

class Car():
    '''car information summary'''

    def __init__(self, make, model, year, odometer=0):
        self.make = make
        self.model = model
        self.year = year
        self.odometer = odometer

So in case you call it with three parameters, Python will see that you did not provide a value for the odometer parameter, and it will implicitly assign zero to it.

A point that sometimes causes confusion is that the default values are only evaluated once, at interpretation time, not each time you call the __init__ function.

For example if we write:

def f(x=[]):
    return x

Then Python will evaluate [] only once. And each time you do not provide a value for x, you will obtain a reference to the same list (not a new list every time).

Therefore it is usally dangerous to use mutable types (an int is not a mutable type, so we are safe for the odometer=0).

If we thus for instance .append(3) to the outcome of f(), then from now on, f() will return that list ([3]). Which is usually not the intended effect. Some IDEs will give warnings if you use a mutable object.

If you want a new empty list each time x is not provided, a common pattern is:

def f(x=None):
    if x is None:
        x = []
    return x

Upvotes: 7

Related Questions