Learn Python - Classes
What are classes in Python? Classes are a user-defined blueprint from which objects can be created.
Python is an Object Oriented Programming
Language. Almost everything in Python is an object including its properties and methods. Classes are a user-defined blueprint from which objects can be created. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state.
class Example:
name = 'Techn0'
Object
An object is an instance of a class. You can create different instances/objects for a class with different properties.
ex = Example
print(ex.name)
Output:
Techn0
__init__()
Method
__init__()
is similar to a constructor and is used to initialize the class's state. It runs as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.
class Example:
def __init__(self, name, age):
self.name = name
self.age = ageex = Example("Techn0", 24)print(ex.name)
print(ex.age)
Output:
Techn0
24
Methods in a Classes
You can also define methods inside a class. A different instance can access the methods with different input parameters.
class Example:
def __init__(self, name, age):
self.name = name
self.age = age def func (self, aim):
print("hello I am " + self.name + " I am a " + aim )
ex = Example("Techn0", 24)print(ex.name)
print(ex.age)ex.func("Engineer")
Output:
Techn0
24
hello I am Techn0 I am a Engineer
Self Parameter
The self
parameter is similar to a pointer in C++, it refers to a particular instance of the class. It is passed along with methods (first parameter) and is used to access variables that belong to the class.
class Example:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)p1 = Example("John", 36)p1.myfunc()
Output:
Hello my name is John
Modify the Object Properties
The change in one instance of the object will not affect other instances.
p1.age = 23
print(p1.age)print(p2.age)
Output:
23
36
The classes form the backbone of oops
programming languages. Here we have discussed the basics of class in Python. Hope you have understood.
For more, you can refer to the following:
For practice and examples, go here:
More content at plainenglish.io. Sign up for our free weekly newsletter. Get exclusive access to writing opportunities and advice in our community Discord.