Skip to main content

object oriented programming with python

Introduction:

Object oriented programming is the newest style of programming. In the history of programming there have been three types of programming.
  • The first style, which can be considered programming in which sense we use programming nowadays, was structural programming. This was really low level programming languages, and even C falls in the same.
  • Then came the functional programming, when, relatively bigger problems came into picture and people started to break down them into small small problems, wrote functions for them, and after that "stitched" them together to solve the main problems. Many of the similar low level languages were of this type.
  • But, then came object oriented programming, which was way cooler and smarter than all these. This abstracted the data out into objects which had actions associated to do, thus created a faster, much more reusable way to deal with problems. This, basically is the current standard. Python , java(partially at least) are example of object oriented programming.

In this post, we will discuss about concepts and examples of object oriented programming using the language python.The concepts discussed are:

  1. what is object?
  2. what is class?
  3. syntax based description
  4. deeper concepts of oop
  5. New perspectives for beginners after oop
  6. Full example of oop use in python
  7. Conclusion and further studies links

what is object?

object, is the most real life imitation of objects in real world, into the programming world. An object, is basically one instance of a class [don't get worried if you just do not understand it at this moment] . So, a object will have data associated with it, which basically signifies its values and its unique existence, and then all of the objects of the same classes, have common attributes, member values, and methods to work with. I will explain with a example below:

If you are a python user, you know about list. Now, each list is a object, while all lists, belong to the class "list". Lists have the input elements, as the data associated with them. Then, there are methods/attributes to work on, i.e. len(), sort(), append() etc functions are associated there, by default with a list. You can access them by  list.sort(), or len(list) or similar ways. So, here you go, hope you get some idea. 

what is class?

A class, in other hand, superficially talking groups of objects. A class, symbolizes the real life classes of objects, like animals or cars, which are real life classes. Now, as car, has properties like colors, no of wheels, sizes; functions as drive, music playing, dashboard showing etc. So, classes has member values and methods. 

Syntax based details description:

Now, I taught myself object oriented programming in python from Codeacademy. Now, below, I will describe syntaxes of class and object using code snippet from codeacademy. 


See, first one introduces class by 
class Classname(ParentClassName):
where ParentClassName refers to the class which is the parent class of the class being declared. ClassName is the name of the class. This is the same as definition of functions which is
def function(args):
The next thing which you need to understand is how to initialize the data which is input. The function used to initialize is def __init__(self,args). here, you should stick with the notion __init__() format, as it is standard. The typical configuration will be:
def __init__(self,arg1, arg2, ..., argN):
   self.arg1=arg1
   self.arg2=arg2
   ...
   self.argN=argN
Now, after that consider the method is check_angles. Things to note here:
(1) we call functions defined inside class are called methods.
(2) As we need to use a object of the class again for the method as argument to access the class's data, we provide the class itself as argument for every method, as self. 
(3) For using any different object of the same class, its not necessary, but you can for general introduce this as other, just like 
def FunctionName(self,other):

Next thing, you need to observe that, if there is some information which is common for all the objects belonging to the class,then we can add the variables with their values inside the class's description. 

Now, we understand that each class can have
  1. member variable or default variables
  2. data
  3. methods
We have to understand the instantiation of a class, which is basically a object

The basic syntax for instantiating a new instance of a class, i.e. a object, is:
ObjectName= ClassName(args)

and for accessing the data or member variable, the syntax is:
ObjectName.memberVariable
ObjectName.data_arg

and for accessing the methods of the object is:
ObjectName.MethodName()

Deeper concepts of object oriented programming:

In this section, we are going to discuss a bit more deep concepts of oop. The concepts are

(1) inheritance: 

In object oriented programming, one starts with most general classes and then go on to define more customized and detailed classes. In this case, we use the parent classes to not repeat the already defined methods. Once you put a parent class's name in the argument of the class definition, it inherits all the class structure of the parent class automatically. After that, you can add further specifications, override, redefine some methods, or use same method name but customize it to be used for the derived class. There are many subtlties here and the scopes, polymorphisms, overrides and other things really play important roles in inheritance. 
But the main thing about the inheritance is that it represents the reusability of code best. All the methods written for the parent class can be used without mentioning in the derived class's definition, while they can be changed or morphed to behave differently for the derived class other than the base class. 

(2) Polymorphism:

polymorphism represents the ability of a language to have different functions with different arguments but same name to work in same program. I will explain the same with example:

def sum(a,b):
   return a+b
def sum(a,b,c):
    return a+b+c
here, both of the programs, have same name, but one has 2 arguments and the other has 3 arguments. 
Therefore, python can run both the programs, although the functions are with same name. This is what polymorphism means. 

This is important in the context of object oriented programming. In a derived class, we can write same named function as in parent class, but with different body and arguments. This therefore, lets the derived class's function to override the function of the parent class. Here, below, I will give another example.

class shape(object):
    def __init__(self,sides):
         self.sides=sides
class triangle(shape):
   no_of_sides=3
   def __init__(self,side1,side2,side3):
        self.side1=side1
        self.side2=side2
        self.side3=side3
 my_triangle=triangle(3,4,5)
Here, the second __init__() function will work when called by the triangle(3,4,5). [whenever, a object is declared, the init function gets called to initialize the instance or the object] Notice that, here the shape is the parent class, but the shape's init function gets overrided by the init in the triangle class.
This is a easy example, but I hope you understand the notion well.


(3)Encapsulation:

In object oriented programming, an idea is to encapsulate the data; i.e. the put the data inside a cover or sort of a layer of coding. In java and ruby, you can clearly mention private, public and protected; to clearly allow different users of the codes and the classes to see what are inside the class.
  But in python and Perl, private is not strictly private. putting two underscores i.e. __FunctionName__() makes the method not accessible directly. The same type of privacy can be accessed by putting one underscore before the function name. But still, there are ways to access the functions( some code like _classname_functionName). Therefore, in python, there is no actual strict privacy; but some amount of privacy can be accessed.

For more on privacy in python, see stackoverflow here.

Neat points to know for beginners:

These are the very basics of object oriented programming. Some things which are new in oop, are basically,
  1. underscored methods

    the classes do not work as simple as the other functional programmings. In python, classes work with the specific placing of underscores; i.e. if you name the init function, not with two underscores, it will not be accessed properly and therefore, you will not be able to declare objects as shown above.

    Also, when objects are used with "+","-","/" symbols; the methods defined inside your classes respectively with the syntaxes, __add__(self,other),__subtract__(self,other), __divide__(self,other) will be accessed immediately. So, you can see, object oriented programming is not too clearly visible in terms of the language's working, i.e., in class structures, there are some internal relations in pythons.

  2. you understand that all the list, dictionary, sets, etc, most of the objects in different modules like regression models in scikit, etc, are objects written in detail under the hood of these names. Each time you define one such object with its specifications; you create an instance of the underlying class and therefore you become able to access all the underlying methods and attributes.

  3. In python, each new class, (in 2.x explicitly and by default in 3.x) inherits from a common parent class object if not specified otherwise. If you are curious about what this object is about, it is a very general class and for more discussion on this, please look here in stack overflow.


Full example of oop use in python

Conclusion:

Object oriented programming is the current way to work on large code bases or any industrial codes. Therefore, it is necessary to start gaining knowledge about it. This post will help you to get a good basis on object-oriented programming in python. While I have discussed the details enough to help you start writing codes on yourself; you can also try your hands on these basics on the interactive training sessions from CodeAcademy. Some more basics which I have not mentioned here are about super calls, indentation specifications, representations of the data of classes,(use of __repr__() function ), driver and constructor parts in oop, etc. I will later add a post on oop with only deeper techniques of oop like these things with maybe a project. Thanks for reading this and for more reading, refer here
 (1) GeeksForGeeks
 (2) mit 6.0001 object oriented programming lectures
 (3)RealPython
 Thanks for reading! 

Comments

Popular posts from this blog

Tinder bio generation with OpenAI GPT-3 API

Introduction: Recently I got access to OpenAI API beta. After a few simple experiments, I set on creating a simple test project. In this project, I will try to create good tinder bio for a specific person.  The abc of openai API playground: In the OpenAI API playground, you get a prompt, and then you can write instructions or specific text to trigger a response from the gpt-3 models. There are also a number of preset templates which loads a specific kind of prompt and let's you generate pre-prepared results. What are the models available? There are 4 models which are stable. These are: (1) curie (2) babbage (3) ada (4) da-vinci da-vinci is the strongest of them all and can perform all downstream tasks which other models can do. There are 2 other new models which openai introduced this year (2021) named da-vinci-instruct-beta and curie-instruct-beta. These instruction models are specifically built for taking in instructions. As OpenAI blog explains and also you will see in our

Can we write codes automatically with GPT-3?

 Introduction: OpenAI created and released the first versions of GPT-3 back in 2021 beginning. We wrote a few text generation articles that time and tested how to create tinder bio using GPT-3 . If you are interested to know more on what is GPT-3 or what is openai, how the server look, then read the tinder bio article. In this article, we will explore Code generation with OpenAI models.  It has been noted already in multiple blogs and exploration work, that GPT-3 can even solve leetcode problems. We will try to explore how good the OpenAI model can "code" and whether prompt tuning will improve or change those performances. Basic coding: We will try to see a few data structure coding performance by GPT-3. (a) Merge sort with python:  First with 200 words limit, it couldn't complete the Write sample code for merge sort in python.   def merge(arr, l, m, r):     n1 = m - l + 1     n2 = r- m       # create temp arrays     L = [0] * (n1)     R = [0] * (n

What is Bort?

 Introduction: Bort, is the new and more optimized version of BERT; which came out this october from amazon science. I came to know about it today while parsing amazon science's news on facebook about bort. So Bort is the newest addition to the long list of great LM models with extra-ordinary achievements.  Why is Bort important? Bort, is a model of 5.5% effective and 16% total size of the original BERT model; and is 20x faster than BERT, while being able to surpass the BERT model in 20 out of 23 tasks; to quote the abstract of the paper,  ' it obtains performance improvements of between 0 . 3% and 31%, absolute, with respect to BERT-large, on multiple public natural language understanding (NLU) benchmarks. ' So what made this achievement possible? The main idea behind creation of Bort is to go beyond the shallow depth of weight pruning, connection deletion or merely factoring the NN into different matrix factorizations and thus distilling it. While methods like knowle