Skip to main content

Classes and Objects in Python

Python is an object-oriented programming language, which means that it provides features that support object-oriented programming.
The basic components of object oriented programming are classes and objects.
A Class is a blue print to create an object. It provides the definition of basic attributes and functions of objects.
Object is a running instance of the class having the identity(name), properties( values) and behaviors(functions).
The Object oriented program thus consist of object definitions (classes) and most of the computations and functions are mentioned as operations on the object.
Each object definition corresponds to some object or concept in the real world, and the functions that operate on these object correspond to the ways real-world objects interact.
We have learned objects of string, list, tuple etc…and used the properties and functionalities of these objects which are built into the Python. Now we are going to create our own(user defined) objects.
The class provides basic definitions of an object, which defines the attributes and methods of an object. Methods are defined inside a class definition in order to make the relationship between the class and the method explicit and are called with the object name.

Lets create a Point class representing a point (x,y) in a two dimensional coordinate system. A point object will have x,y values and also member functions to initialize and print the values.

class Point:
  def  __init__(self,x=0,y=0): 
  def printpoint(self):
        print "("+str(self.x)+','+str(self.y)+")"


The class definition is similar to function definition
class Point:
will create a namespace for the class Point.

Constructors in Python (Using __init__)
A constructor is a special method that is used to initialize the data members of a class. In python, the built in method __init__ is a sort of constructor. Notice the double underscores both in the beginning and end of init. In fact it is the first method defined for the class and is the first piece of code executed in a newly created instance of the class. The constructor will be executed automatically when the object is created.
Methods are member functions defined inside the class, which gives the functionality. Class methods have only one specific difference from ordinary functions - they must have an extra argument in the beginning of the parameter list. This particular argument is self which is used for referring to the instance. But you need not give any value for this parameter, when you call the method. Self is an instance identifier and is required so that the statements within the methods can have automatic access to the current instance attributes.

Class Instances(Objects)
Having a class defined, you can create as many objects as required. These objects are called instances of this class. The process of creating objects is called instantiation.
All the instances created with a given class will have the same structure and behavior. They will only differ regarding their state, i.e regarding the value of their attributes.
To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.
In the above example two instance of the class is created. One Point object with default values ie;(0,0) and the other with value (10,20).

Attribute Reference: Accessing attributes of a class
Classes and instances have their own namespaces, that is accessible with the dot ('.') operator.
This is the standard syntax used for all attribute references which is 
Object Name. Attribute Name.
As discussed before all the names that were given during the class definition and hence were in the class's namespace are valid attribute names. You access the object's attributes using the dot operator with object as shown in the example above :

When you say Hari and I have the same car, you mean that his car and yours are the same make and model, but that they are two different cars.
If you say, “Chris and I have the same mother,” you mean that his mother and yours are the same person. So the idea of “sameness” is different depending on the context.
When you talk about objects, there is a similar ambiguity. For example, if two Points are the same, does that mean they contain the same data (coordinates) or that they are actually the same object?
For example consider the code below
Print P1==P2
Print P1 is P2
It is noted that both print statement will print False even though they contain the same data, they refer to two different objects. If we assign P2=P1, they refer to the same object.
Print P1 is P2
This will print True because both P1 and P2 is now referring the same object. You can check id(P1) and id(P2).
This type of equality is called shallow equality because it compares only the references, not the contents of the objects.
If you want to compare the actual contents of the object ie; deep equality, we have to write a separate function like this
def compare(P1,P2):
            return (P1.x==P2.x) and (P1.y==P2.y)
Now if we create two different objects that contain the same data, we can use compare(P1,P2) function to find out if they represent the same point.

Sample Programs
Lets create another class Arith to do arithmetic operation. It contains a member function read() to read the two numbers and add() method to find the sum. You can add more methods to the class to incorporate more functionality.

class Arith:
    def read(self):
        self.x=input("enter first number..")
        self.y=input("enter second number...")
    def add(self):
        print "sum=",self.x+self.y
#creating an object
#calling the methods

Lets create another class Rectangle .A constructor is used to initialize the object values. Member function area() compute the area of the rectangle ( university question)
class Rectangle:
    def __init__(self,length=0,breadth=0):
    def area(self):
        print "area=",self.length*self.breadth
Create a class car with attributes model, year and price and a method cost() for displaying the prize. Create two instance of the class and call the method for each instance.(university question)
class Car:
     def __init__(self,model,year,prize):
     def cost(self):
        print "Prize of the car=",self.prize
Create a class student with attribute name and roll number and a method dataprint() for displaying the same. Create two instance of the class and call the method for each instance.( university question)
class Student:
    def __init__(self,name,rno):
    def dataprint(self):
        print "Name=",
        print "Rno=",self.rno
Create a class Person with attributes name, age salary and a method display() for showing the details. Create two instances of the class and call the method for each instance.
class Person:
    def __init__(self,name,age,salary):
    def display(self):
        print "Name=",
        print "Age=",self.age
        print "Salary=",self.salary
Try the following programs in lab (University questions)
1.Create a class Rectangle with attributes length and breadth and method area() for calculating the area of the rectangle. Create two instances of the class and call the method for each instance.
2. Create a class car with attributes model, year and price and a method cost() for displaying the prize. Create two instance of the class and call the method for each instance.
3. Create a class student with attribute name and roll number and a method dataprint() for displaying the same. Create two instance of the class and call the method for each instance.
4. Create a class Person with attributes name, age, salary and a method display() for showing the details. Create two instances of the class and call the method for each instance.
5.Create a class Employee with attributes name, age and salary and a method printdetails() for displaying the same. Create two instances of the class and call the method for each instance.


Popular posts from this blog

Files in Python , Exception handling

While a program is running, its data is in main memory. When the program ends, or the computer shuts down, data in memory disappears. To store data permanently, you have to put it in a file. Files are usually stored on a secondary storage device(hard disk, pen drive, DVD,CD etc). When there are a large number of files, they are often organized into directories (also called “folders”). Each file is identified by a unique name, or a combination of a file name and a directory name. By reading and writing files, programs can exchange information with each other and generate printable formats like PDF. Working with files is a lot like working with books. To use a book, you have to open it. When you’re done, you have to close it. While the book is open, you can either write in it or read from it. In either case, you know where you are in the book. Most of the time, you read the whole book in its natural order, but you can also skip around. All of this applies to files as well. To open a fil…

User Defined Functions in Python

So far we have only seen the functions which come with Python either in some file (module) or in interpreter itself (built in), but it is also possible for programmer to write their own function(s) and are called User Defined Functions. These functions can then be combined to form a module which can then be used in other programs by importing them.
In the context of programming, a function is a named sequence of statements that performs a desired operation. This operation is specified in a function definition.
To define a function keyword def is used. After the keyword comes an identifier of the function, followed by parenthesized list of parameters and the colon which ends up the line. Next follows the block of statement(s) that are the part of function. A block is one or more lines of code, grouped together so that they are treated as one big sequence of statements while executing. In Python, statements in a block are written with indentation. Usually, a block begins when a li…

Dictionary In Python

Dictionaries are similar to other compound types except that they can use any immutable type as an index. We can refer to a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps a value. The association of a key and a value is called a key-value pair. A dictionary is an extremely useful data storage construct for storing and retrieving all key value pairs, where each element is accessed (or indexed) by a unique key. However, dictionary keys are not in sequences.
            Dictionaries are mutable.             Dictionaries are unordered. Items in dictionaries are accessed via keys and not via their position. A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped) to a value. The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-pairs.  Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and…