Classes - Python (2016)

Python (2016)

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.

Constructing Classes

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:

Class <<name>>:

Def <<method>> (self [, <<optional arguments>>]):

<<Function codes>>

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:

Class Motorcycle:

Def brakes(self):

Print“Braking”

Def accelerates (self):

Print “Accelerating”

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

Motorcycle1.brakes()

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.

Properties

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:

Motorcycle1.color=”Blue”

Then, this value is retrieved as:

Print motorcycle1.color

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:

Class motorcycle:

...previous methods...

Def set_owner(self,Owner_Name): #This part sets the “owner“ property.

Self._owner=Owner_Name

Def get_owner(self): # This part will retrieve the same property.

Return self._owner

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:

Class motorcycle:

...previous methods...

Owner=property(get_owner, set_owner)

Then, when you call in a way like mymotorcycle.owner=”John Doe”, the function set_owner is called transparently instead.

Class Extension

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:

class new_motorcycle(motorcycle):

Def start_motorcycle(self):

Self.on=True

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:

Class new_motorcycle(motorcycle):

Def __init__ (self,model,brand,year):

# This sets all the properties

Self.brand=model

Self.model=brand

Self.year=year

Def start_motorcycle(self):

“””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”)

Motorcycle1.start_motorcycle()