python


Python Classes and Objects


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.

Create Class
To create a class, we will use the class keyword. Syntax:
class classname:
Example:
class Count:
x=20
As you can see above we used the class keyword to define a class named Count.
Create Object

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.


Syntax:
objectname=classname()
Example:
obj1=Count()
The __init()__ Function

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.

Example:

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
Object Methods

Objects can also contains methods, these methods in objects are functions that belong to the object.

Example:

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

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.


Example:

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.

Modify Objects Properties

Object properties can be modified:

p1.pclass='10th'
Delete Objects Properties

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.

The pass statement

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