Classes
Python makes
object-oriented programming easy. The class
statement begins the definition of a class. Classes can use a special
constructor called __init__(
)
to initialize
their data. Because Python doesn’t declare variables, this
constructor is a common place to initialize any variables the class
may require:
>>> 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
self
each time you access an
attribute.
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.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access