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

Mastering SQL for Data Science: Top SQL Interview Questions by Experience Level

Introduction: SQL (Structured Query Language) is a cornerstone of data manipulation and querying in data science. SQL technical rounds are designed to assess a candidate’s ability to work with databases, retrieve, and manipulate data efficiently. This guide provides a comprehensive list of SQL interview questions segmented by experience level—beginner, intermediate, and experienced. For each level, you'll find key questions designed to evaluate the candidate’s proficiency in SQL and their ability to solve data-related problems. The difficulty increases as the experience level rises, and the final section will guide you on how to prepare effectively for these rounds. Beginner (0-2 Years of Experience) At this stage, candidates are expected to know the basics of SQL, common commands, and elementary data manipulation. What is SQL? Explain its importance in data science. Hint: Think about querying, relational databases, and data manipulation. What is the difference between WHERE ...

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 know...

Spacy errors and their solutions

 Introduction: There are a bunch of errors in spacy, which never makes sense until you get to the depth of it. In this post, we will analyze the attribute error E046 and why it occurs. (1) AttributeError: [E046] Can't retrieve unregistered extension attribute 'tag_name'. Did you forget to call the set_extension method? Let's first understand what the error means on superficial level. There is a tag_name extension in your code. i.e. from a doc object, probably you are calling doc._.tag_name. But spacy suggests to you that probably you forgot to call the set_extension method. So what to do from here? The problem in hand is that your extension is not created where it should have been created. Now in general this means that your pipeline is incorrect at some level.  So how should you solve it? Look into the pipeline of your spacy language object. Chances are that the pipeline component which creates the extension is not included in the pipeline. To check the pipe eleme...