All modern day programming languages are based on the concept of OOP – object oriented programming and support classes and objects. Python too is an object oriented language right from the very beginning. Let’s have a look at the basics of object oriented programming. An object is creating or encapsulating your customized group of variables that has its own set of attributes, functions and properties. A call defines all the characteristics and properties of an object. The object can access methods with the help of dot notation. A variable that holds data values associated with a class and its objects is known as data member.
Following are some more terms that you would need to know about Python classes/objects:
1. A variable that is defined inside a method of a class and can be accessed only by the instance of that class are called instance variable.
2. If you derive a class from another class such that it has all the characteristics of the parent class is called Inheritance.
3. An object of a class is also known as an instance.
4. When you create an instance of a class it is called instantiation.
5. A function that is part of class definition is known as a method
The syntax for defining a class is as follows:
class Class_Name: code_functions_variables
The syntax for creating an object is:
object_name = Class_Name()
Now let’s try to understand how a class works with the help of a simple example:
class Hello_World: def hello_world(self,x): self.x = x print(x) obj_hellow = Hello_World() obj_hellow.hello_world("Hello World")
In Python, in every function, the first argument refers to its current instance and this argument is the self. Notice this in the code above. When we make a call to a function we don’t pass any value for self.
If there is a need to customize an object to an initial state when it is created then you will have to define an __init__() function in the class. Look at the following piece of code:
class Hello_World: def __init__ (self, x): self.x = x obj_hellow = Hello_World("Hello World") print(obj_hellow.x)
So, here you can see when you create the object, a string value “Hello World” is passed as an argument. The __init__() function assigns this value to the attribute x. So, to access this value you can access the variable with a dot notation obj_hellow.x.