You are on page 1of 1

Use object as first parent

This is tricky, but it will bite you as your program grows. There are old and new classes in Python 2.x. The old ones
are, well, old. They lack some features, and can have awkward behavior with inheritance. To be usable, any of your
class must be of the "new style". To do so, make it inherit from object.

Don't:

class Father:
pass

class Child(Father):
pass

Do:

class Father(object):
pass

class Child(Father):
pass

In Python 3.x all classes are new style so you don't need to do that.

Don't initialize class attributes outside the init method

People coming from other languages find it tempting because that is what you do in Java or PHP. You write the class
name, then list your attributes and give them a default value. It seems to work in Python, however, this doesn't
work the way you think. Doing that will setup class attributes (static attributes), then when you will try to get the
object attribute, it will gives you its value unless it's empty. In that case it will return the class attributes. It implies
two big hazards:

If the class attribute is changed, then the initial value is changed.

If you set a mutable object as a default value, you'll get the same object shared across instances.

Don't (unless you want static):

class Car(object):
color = "red"
wheels = [Wheel(), Wheel(), Wheel(), Wheel()]

Do:

class Car(object):
def __init__(self):
self.color = "red"
self.wheels = [Wheel(), Wheel(), Wheel(), Wheel()]

Section 200.2: Mutable default argument


def foo(li=[]):
li.append(1)
print(li)

GoalKicker.com – Python® Notes for Professionals 765

You might also like