Basics of object orientation in Python
2020.02.25 Python CodementorPython has support for object orientation, and can (totally optionally, of course) be used to write more modular Python scripts, and better-defined APIs.
The implementation of object orientation in Python is a pretty simple one, and if you want to get into this style of programming, probably a good place to start. Much simpler, for example, than C++.
Essentially, a class is just a way to bundle a data structure, containing relevant information about a thing, and methods, functions which are attached to that thing, together. Such objects can be used to make a cleaner API.
A basic python class could be:
class Dog: barks = 0 def __init__(self): print "called Dog constructor" def pet(self): self.barks += 1 print "woof woof"
In the above, self
is a handle to access the specific instance of the class,
including its member variables, its state.
__init__
is a magic Python function name which means that this method is the
constructor of the class, and is called when the class is instantiated as
follows:
d = Dog()
The variable d
is now an instance of the Dog class, and can be interacted
with, e.g. in the Python repl, by running python
:
>>> d = Dog() called Dog constructor >>> d <__main__.dog instance at 0x7f183cc051e0> >>> d.barks 0 >>> d.pet() woof woof >>> d.barks 1 >>> d.pet() woof woof >>> d.barks 2
It's clear that the class instance has remembered its state, the number of barks.
In most cases, Python classes are often written as below, which covers up the
member variable barks
somewhat, by creating it within the constructor:
class Dog: def __init__(self): self.barks = 0 print "called Dog constructor" def pet(self): self.barks += 1 print "woof woof"
This is possible, since Python is a dynamic language, and such things (adding a member variable to the class) can be done trivially at run time, since no checking has to be done by a compiler.
If you wish to use parameters when you set up an object, this can be done with the constructor:
class Dog: def __init__(self, initial_barks): self.barks = initial_barks def pet(self): self.barks += 1 print "woof woof"
Calling this could work as follows:
>>> d = Dog(42) called Dog constructor >>> d.barks 42 >>> d.pet() woof woof >>> d.barks 43
There are further features of object orientated programming, including encapsulation, inheritance and polymorphism, this being the basics, they won't be covered in this post.