Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

1) Python Class and Objects: Creating Classes in Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

1)Python Class and Objects

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.

Creating classes in Python


In Python, a class can be created by using the keyword class, followed by the class name.
The syntax to create a class is given below.

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.

Consider the following example to create a class Employee which contains two fields as


Employee id, and name.

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.

Creating an instance of the class


A class needs to be instantiated if we want to use the class attributes in another class or
method. A class can be instantiated by calling the class using the class name.

The syntax to create the instance of the class is given below.

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.

Delete the Object


We can delete the properties of the object or object itself by using the del keyword.
Consider the following example.

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.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.


Create a Class
To create a class, use the keyword class:

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 »

The __init__() Function


The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.

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.

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
Create a class named Person, use the __init__() function to assign values for
name and age:

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 »

Note: The __init__() function is called automatically every time the class is


being used to create a new object.

Object Methods
Objects can also contain methods. Methods in objects are functions that belong
to the object.

Let us create a method in the Person class:

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.

The self Parameter


The self parameter is a reference to the current instance of the class, and is
used to access variables that belongs 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 »

Modify Object Properties


You can modify properties on objects like this:

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 »

The pass Statement


class definitions cannot be empty, but if you for some reason have
a class definition with no content, put in the pass statement to avoid getting an
error.

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

Following is the example of a simple Python class −


class Employee:
'Common base class for all employees'
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

 The variable empCount is a class variable whose value is shared among all


instances of a this class. This can be accessed as Employee.empCount from
inside the class or outside the class.
 The first method __init__() is a special method, which is called class constructor
or initialization method that Python calls when you create a new instance of this
class.
 You declare other class methods like normal functions with the exception that
the first argument to each method is self. Python adds the self argument to the
list for you; you do not need to include it when you call the methods.

Creating Instance Objects


To create instances of a class, you call the class using class name and pass in
whatever arguments its __init__ method accepts.
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)

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 __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

When the above code is executed, it produces the following result −


Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2
You can add, remove, or modify attributes of classes and objects at any time −
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
del emp1.age # Delete 'age' attribute.
Instead of using the normal statements to access attributes, you can use the following
functions −
 The getattr(obj, name[, default]) − to access the attribute of object.
 The hasattr(obj,name) − to check if an attribute exists or not.
 The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then
it would be created.
 The delattr(obj, name) − to delete an attribute.
hasattr(emp1, 'age') # Returns true if 'age' attribute exists
getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age') # Delete attribute 'age'

Built-In Class Attributes


Every Python class keeps following built-in attributes and they can be accessed using
dot operator like any other attribute −
 __dict__ − Dictionary containing the class's namespace.
 __doc__ − Class documentation string or none, if undefined.
 __name__ − Class name.
 __module__ − Module name in which the class is defined. This attribute is
"__main__" in interactive mode.
 __bases__ − A possibly empty tuple containing the base classes, in the order of
their occurrence in the base class list.
For the above class let us try to access all these attributes −

Live Demo
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

print "Employee.__doc__:", Employee.__doc__


print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__

When the above code is executed, it produces the following result −


Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}

Destroying Objects (Garbage Collection)


Python deletes unneeded objects (built-in types or class instances) automatically to
free the memory space. The process by which Python periodically reclaims blocks of
memory that no longer are in use is termed Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an
object's reference count reaches zero. An object's reference count changes as the
number of aliases that point to it changes.
An object's reference count increases when it is assigned a new name or placed in a
container (list, tuple, or dictionary). The object's reference count decreases when it's
deleted with del, its reference is reassigned, or its reference goes out of scope. When
an object's reference count reaches zero, Python collects it automatically.
a = 40 # Create object <40>
b = a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>

del a # Decrease ref. count of <40>


b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>
You normally will not notice when the garbage collector destroys an orphaned instance
and reclaims its space. But a class can implement the special method __del__(), called
a destructor, that is invoked when the instance is about to be destroyed. This method
might be used to clean up any non memory resources used by an instance.

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

When the above code is executed, it produces following result −


3083401324 3083401324 3083401324
Point destroyed
Note − Ideally, you should define your classes in separate file, then you should import
them in your main program file using import statement.

4)
What are Classes and Objects?

A class is a collection of objects or you can say it is a blueprint of objects defining


the common attributes and behavior. Now the question arises, how do you do that?

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.

Class is defined under a “Class” Keyword.


Example:

1 class class1(): // class 1 is the name of the class


Note: Python is not case-sensitive.

 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()

Here obj is the “object “ of class1.


Explanation: ’emp1′ and ’emp2′ are the objects that are instantiated against the
class ’employee’.Here, the word (__dict__) is a “dictionary” which prints all the values
of object ‘emp1’ against the given parameter (name, age, salary).(__init__) acts like a
constructor that is invoked whenever an object is created.

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:

#Collection of statements or functions or classes


Example:
class MyClass:
a = 10
b = 20
def add():
sum = a+b
print(sum)
In the above example, we have declared the class called ‘Myclass’ and we have declared
and defined some variables and functions respectively.

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:

You might also like