Professional Documents
Culture Documents
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.
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 you set a mutable object as a default value, you'll get the same object shared across instances.
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()]