object-oriented programming easy. The
statement begins the definition of a class. Classes can use a special
their data. Because Python doesn’t declare variables, this
constructor is a common place to initialize any variables the class
>>> class Car: ... def __init__(self): ... self.milespergallon = 25.0 ... self.travelled = 0 ... self.color = 'blue' ... self.gas = 20 ... def drive(self, miles): ... self.travelled = self.travelled + miles ... self.gas = self.gas - (miles / self.milespergallon) ... >>> c = Car() >>> c.drive(100) >>> c.travelled 100 >>> c.gas 16.0 >>>
Note that you have to use the keyword
each time you access an
As with other languages, classes may inherit from a base class and be initialized with arguments supplied by the constructor. We won’t give any further examples at this point; you can see many classes throughout this book, and the syntax is self-evident if you are used to object-oriented programming.