As we know, Python is an object oriented programming language(OOP)
A class can be defined as a "blueprint"of objects or a group of objects.
class classname:
Example:
class Count:
x=20
As you can see above we used the class keyword to define a class named Count.
We also discussed something about in the section of OOP.
An Object can be defined as an identifiable entity which has some attributes and behaviour.
objectname=classname()
Example:
obj1=Count()
The above mentioned classes are simplest. These cannot be used in real-life applications.
For real-life applications, we need to understand the __init__() function which is built in function.
All classes consist of a function called __init__() which is always executed when the class is being initiated.
The __init__() function is used to assign values to object properties and for some other operations also which are important in python.The __init__() function is automatically called when the class is used to being create its object.
class Student:
def __init__(self, name,pclass):
self.name = name
self.pclass = pclass
p1 = Student("Sushant", '9th')
print(p1.name)
print(p1.pclass)
Output:
Sushant
9th
Objects can also contains methods, these methods in objects are functions that belong to the object.
class Student:
def __init__(self, name,pclass):
self.name = name
self.pclass = pclass
def func(self):
print("Hii my name is "+ self.name + ".I am in class " + self.pclass)
p1 = Student("Sushant", '9th')
p1.func()
Output:
Hii my name is Sushant.I am in class 9th
The self parameter is a reference to the current instance of class. And we use this parameter to access variables that belongs to the class.
Note: The parameter does not named to be self you can named it anything you like. But it should be the first parameter of any function present in the class.
class Student:
def __init__(justaname, name,pclass):
justaname.name = name
justaname.pclass = pclass
def func(justaname2):
print("Hii my name is "+ justaname2.name + ".I am in class " + justaname2.pclass)
p1 = Student("Sushant", '9th')
p1.func()
Output:
Hii my name is Sushant.I am in class 9th
You can see in the above code we used justaname and justaname2 in the place of self and it works well.
Object properties can be modified:
p1.pclass='10th'
Properties of objects can be deleted by del keyword.
del p1.pclass
Note:You can also delete the whole object by using del objectname code.
As we know we have class definitions in class and it cannot be empty. So here we use pass statement.
The pass statement is used if we don'tb have any content for class definitions.
class Car:
pass