Python Classes and Objects
In Python OOPS introduction, we came to know that what are classes and objects in Python. Now, we are going to learn about Classes and Objects in brief.
Python Classes/Objects
As all of us know that, Python is an object-oriented programming language. Almost everything in Python is considered as an object, with its properties and methods. For Example, Lists, Tuples, Sets, Dictionaries, etc. In other words, Python Object is simply a collection of data (variables) and methods (functions) that act on those data.
Python Classes
Classes are like the object constructor. Or we can say “blueprint” for creating objects.
Example of creating Python class
class MyClass:
x = 5
print(MyClass)
Description about program
Here, we have created a class named MyClass, with a property named x.
<class ‘__main__.myclass’=””>
Python Object
Above we created a class, now we can use the class named myClass to create objects
Example of Python object
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
Description about program
Here, we used the class name to create it’s object named p1. With the help of object, we will access the class property.
5
The __init__() Function
To understand the meaning of classes we have to understand the built-in __init__()
function.
All classes have a function called __init__()
, which is always executed when the class is being initiated.
Mostly we use the __init__()
function to assign values to object properties, or other operations that are necessary to do when the object is being created
Example to create a class constructor using __init__() function
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Description about program
Here, we created a class Person, and used the __init__()
function to assign values for name and age:
John
36
Note: The __init__() function is called automatically every time the class is being used to create a new object.
Exercises & Assignments |
---|
No Content Found. |
Interview Questions & Answers |
---|
No Content Found. |