Like may other programming languages, Python also has the concept of classes and objects. In this article we will create a Python class example and perform some operations using objects. A class typically consists of constructor, variables and functions. Objects of classes may access any attribute(variables, functions) using “.” symbol like <objectName>.<attributeName>.
When we define a class, it creates a new type in Python. Python classes are created by using the keyword class.
class <className>: <statement....1> ..... <statement....2>
In some cases while creating an object of a class, it may require an initial state. To achieve this, Python has a special function __init__(). This function gets called every time when an object of the class is created. Function __init__() also accepts arguments. Consider the below example of Python class that has __init__() function.
class Example: def __init__(self, x, y): self.x = x self.y = y myclass1 = Example(5,10) print(myclass1.x)
Here we created an object of a class Example and initialized it using __init__(). The output of above Python code will be “5”.
Python Class – Example
Let us take a quick look at how we can define a class that included variables, functions and classes.
class Example: def __init__(self, x, y): self.x = x self.y = y def incrementX(self): self.x = self.x + 1 #Create objects of class myclass1 = Example(5,10) myclass1.incrementX() print("X From myClass1 : ",myclass1.x) myclass2 = Example(5,10) print("X From myClass2 : ",myclass2.x)
X From myClass1 : 6 X From myClass2 : 5
Here we have 2 variables defined and we are initializing them using a constructor. We also have defined a function “incrementX()” to increment the value of variable x. In our example we are creating 2 objects and observe the value of ‘x’ in both objects. Both the objects get their own copy of the variable. So the increment we have done on first object (myclass1) didn’t affect the variable ‘x’ in second object (myclass2).