Object Oriented Python Programming


In python object oriented programming is a simple way to build powerful applications. Consider a real-world object like a pair of shorts. This pair of shorts has a set of attributes and properties to make that pair of shorts unique. For example this pair of shorts might have pockets, buttons and zippers to put on and take off the shorts. Essentially, we have a blueprint to make any pair of shorts (give or take a few unique properties), this is known as a class and is the fundamental concept of object oriented programming and design. Each class defines attributes and methods instantiated by objects. Let’s take a look at some example code of out shorts class.

class shorts:
    def __init__(self,waist,length,color):

In python each class has an __init__ constructor to define unique parameters for each object. Self is the reference to the object at reference and initializes attributes unique to that class. Above, the constructor class takes parameters self, waist length and color and initializes those values as arguments utilized later in the program. Put on and take off methods pass those arguments by reference and updates self.wearing to false to let us know the shorts are off.

    def put_on(self):
        print("Putting on {}x{} {} shorts".format(self.waist,self.length,self.color))

    def take_off(self):
       print("Taking off {}x{} {} shorts".format(self.waist,self.length,self.color))


The code above defines methods to handle attributes of the shorts object ie. self.waist, self.length, self.color and self.wearing. When executed the passed attributes are printed to the console. The code below shows the class, instantiated as an object calling the defined methods.

new_shorts= shorts(32,33,"blue")


Screenshot (6)

If you like these blog posts or want to comment and or share something do so below and follow py-guy!