CHAPTER 18: Classes
Object Oriented Programming
Object oriented programming (OOP) is an approach to programming where the objects are defines using methods (actions, functions, or events) and properties (characteristics, values). This results in a more readable and more reusable code.
Take for example, a scenario where you have to write a program in order to keep track of a group of motorcycles. Each of these vehicles have different characteristics, such as color, mileage, etc. However, all of these perform the same basic actions such as accelerating, braking, and swerving in and out of traffic. So instead of writing a piece of code separately for each of these motorcycles, one can simply create a class for it—this can serve as the “blueprint” for each of the objects.
A “class” is basically anything that can be said to be the generic description of the object in question. In the Python programming language, a class method (an event, function, or action) is defined. This is done using the following structure:
Def <<method>> (self [, <<optional arguments>>]):
Let us discuss this in detail. First, the object is defines using the keyword ‘class’, the name that we want, and the colon as a punctuation. The methods are defined as in a normal function—a single indent with ‘self’ as the first argument. So the following can serve as the example class for our motorcycles:
Def accelerates (self):
Note that the first name of the classes should have a capitalized first name. This is quite a common convention, though it is not a technical requirement from the language. Also, the example is a type of “encapsulation”, where the instructions for processing are defined as a part of a different structure for reuse in the future.
How is this used? Once the class is created, then one will have to program an object for each of the class’s instances. In the Python language, programmers create new variables for each of these instances. Here is an example:
Motorcycle1= Motorcycle() # This is the instance for the motorcycle
Motorcycle2 = Motorcycle()
#Now, the object method is used like
By using the parentheses (also called “calling in” the class), you can tell Python that you wish to create not just a copy of the class definition but an instance. You would have to create a different variable for each motorcycle. However, each of these objects can now take advantage of the different attributes and class methods, so you would not have to write a different accelerate and brake function for each of these vehicles.
As of now, all of the motorcycles in the previous sample code look the same. Since that is unacceptable, let us try to give them some properties to make them unique.
In Python programming, a property is simple a variable specifically paired to a given object. In order to assign a property, it is written as:
Then, this value is retrieved as:
For purposes of convention, the functions are written to get (retrieve) and set (assign) properties not set to be “read-only”. Here is an example:
Def set_owner(self,Owner_Name): #This part sets the “owner“ property.
Def get_owner(self): # This part will retrieve the same property.
You might have noticed the underscore that is before the name of the property. This is a way to hide the name of the variable from users.
Starting from Python 2.2, the programmer can also define the example we provided above so that it looks like any normal variable:
Then, when you call in a way like mymotorcycle.owner=”John Doe”, the function set_owner is called transparently instead.
In the event that a programmer will need to place additional functions to the class but is reluctant to change the code (perhaps fearing that this can mess up programs depending on the current version), he can “extend” the class as a solution. When this is done, all the parent methods and properties are inherited while new ones can be added. As an example, one can add a start_motorcycle method to the class. In order to extend classes, the programmer will have to supply the parent’s class name in parentheses right after the new class name. This is shown below:
The new class will extend the parent class.
Note that when attributes and methods are passed down in hierarchies to new classes, the process is referred to in Python as “inheritance”.
Special Class Methods
In the Python language, the special methods’ names begin with double underscores (“__”) and end with the same. For example, a special method __init__ has been used to initialize newly created object states. As an example, the programmer can create not just a new motorcycle model but also set its brand, year, model, and other attributes on a single line. This is opposed to expending additional lines for each of the attributes.
Here is a demonstration:
Def __init__ (self,model,brand,year):
# This sets all the properties
“””Start the motorcycle engine”””
Print “broooom broooom!”
If __name__ == “__main__”:
# This creates two separate instances of new_motorcycle, each of which has unique properties
Motorcycle1 = new_motorcycle(“Diavel”,”Ducati”,”2016”)