1) Python Class and Objects: Creating Classes in Python
1) Python Class and Objects: Creating Classes in Python
1) Python Class and Objects: Creating Classes in Python
We have already discussed in previous tutorial, a class is a virtual entity and can be seen as
a blueprint of an object. The class came into existence when it instantiated. Let's
understand it by an example.
Suppose a class is a prototype of a building. A building contains all the details about the
floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on
these details. Hence, the building can be seen as a class, and we can create as many
objects of this class.
On the other hand, the object is the instance of a class. The process of creating an object
can be called instantiation.
In this section of the tutorial, we will discuss creating classes and objects in Python. We will
also discuss how a class attribute is accessed by using the object.
Syntax
1. class ClassName:
2. #statement_suite
In Python, we must notice that each class is associated with a documentation string which
can be accessed by using <class-name>.__doc__. A class contains a statement suite
including fields, constructor, function, etc. definition.
The class also contains a function display(), which is used to display the information of
the Employee.
Example
1. class Employee:
2. id = 10
3. name = "Devansh"
4. def display (self):
5. print(self.id,self.name)
Here, the self is used as a reference variable, which refers to the current class object. It is
always the first argument in the function definition. However, using self is optional in the
function call.
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class
variables. We can use anything instead of self, but it must be the first parameter of any
function which belongs to the class.
1. <object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee defined in the above
example.
Example
1. class Employee:
2. id = 10
3. name = "John"
4. def display (self):
5. print("ID: %d \nName: %s"%(self.id,self.name))
6. # Creating a emp instance of Employee class
7. emp = Employee()
8. emp.display()
Output:
ID: 10
Name: John
In the above code, we have created the Employee class which has two attributes named id
and name and assigned value to them. We can observe we have passed the self as
parameter in display function. It is used to refer to the same class attribute.
We have created a new instance object named emp. By using it, we can access the
attributes of the class.
Example
1. class Employee:
2. id = 10
3. name = "John"
4.
5. def display(self):
6. print("ID: %d \nName: %s" % (self.id, self.name))
7. # Creating a emp instance of Employee class
8.
9. emp = Employee()
10.
11. # Deleting the property of object
12. del emp.id
13. # Deleting the object itself
14. del emp
15. emp.display()
It will through the Attribute error because we have deleted the object emp.
2)Python Classes/Objects
Python is an object oriented programming language.
Example
Create a class named MyClass, with a property named x:
class MyClass:
x = 5
Try it Yourself »
Create Object
Now we can use the class named MyClass to create objects:
Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
Try it Yourself »
All classes have a function called __init__(), which is always executed when the
class is being initiated.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Try it Yourself »
Object Methods
Objects can also contain methods. Methods in objects are functions that belong
to the object.
Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Try it Yourself »
Note: The self parameter is a reference to the current instance of the class,
and is used to access variables that belong to the class.
It does not have to be named self , you can call it whatever you like, but it has
to be the first parameter of any function in the class:
Example
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Try it Yourself »
Example
Set the age of p1 to 40:
p1.age = 40
Try it Yourself »
Delete Object Properties
You can delete properties on objects by using the del keyword:
Example
Delete the age property from the p1 object:
del p1.age
Try it Yourself »
Delete Objects
You can delete objects by using the del keyword:
Example
Delete the p1 object:
del p1
Try it Yourself »
Example
class Person:
pass
3)
Creating Classes
The class statement creates a new class definition. The name of the class immediately
follows the keyword class followed by a colon as follows −
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string, which can be accessed
via ClassName.__doc__.
The class_suite consists of all the component statements defining class
members, data attributes and functions.
Example
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable
would be accessed using class name as follows −
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Now, putting all the concepts together −
Live Demo
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
Live Demo
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
Example
This __del__() destructor prints the class name of an instance that is about to be
destroyed −
Live Demo
#!/usr/bin/python
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print class_name, "destroyed"
pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
4)
What are Classes and Objects?
Well, it logically groups the data in such a way that code reusability becomes easy. I
can give you a real-life example- think of an office going ’employee’ as a class and all
the attributes related to it like ’emp_name’, ’emp_age’, ’emp_salary’, ’emp_id’ as the
objects in Python. Let us see from the coding perspective that how do you
instantiate a class and an object.
Objects:
Objects are an instance of a class. It is an entity that has state and behavior. In a
nutshell, it is an instance of a class that can access the data.
Syntax: obj = class1()
I hope now you guys won’t face any problem while dealing with ‘classes’ and
‘objects’ in the future.
4)
Classes and Objects
Python is an object-oriented programming language where programming stresses
more on objects.
Almost everything in Python is objects.
Classes
Class in Python is a collection of objects, we can think of a class as a blueprint or sketch or
prototype. It contains all the details of an object.
In the real-world example, Animal is a class, because we have different kinds of Animals in
the world and all of these are belongs to a class called Animal.
Defining a class
In Python, we should define a class using the keyword ‘class’.
Syntax:
class classname:
To access those functions or variables present inside the class, we can use the class name
by creating an object of it.
First, let's see how to access those using class name.
Example:
class MyClass:
a = 10
b = 20
#Accessing variable present inside MyClass
print(MyClass.a)
Output
10
Output:
Objects
An object is usually an instance of a class. It is used to access everything present inside the
class.
Creating an Object
Syntax:
variablename = classname
Example:
ob = MyClass()
This will create a new instance object named ‘ob’. Using this object name we can access all
the attributes present inside the class MyClass.
Example:
class MyClass:
a = 10
b = 20
def add(self):
sum = self.a + self.b
print(sum)
#Creating an object of class MyClass
ob = MyClass()
#Accessing function and variables present inside MyClass using the object
print(ob.a)
print(ob.b)
ob.add()
Output:
10
20
30
Output: