O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required