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): 
        self.x=x
        self.y=y
  def printpoint(self):
        print "("+str(self.x)+','+str(self.y)+")"

P1=Point()
P1.printpoint()
P2=Point(10,20)
P2.printpoint()

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
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).
P1=Point()
P2=Point(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 :
P1.printpoint()
P2.printpoint()
Sameness
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
P1=Point(10,20)
P2=Point(10,20)
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.
P2=P1
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
A=Arith()
#calling the methods
A.read()
A.add()

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):
        self.length=length
        self.breadth=breadth
    def area(self):
        print "area=",self.length*self.breadth
R1=Rectangle(10,20)
R1.area()
R2=Rectangle(12,13)
R2.area()
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):
        self.model=model
        self.year=year
        self.prize=prize
     def cost(self):
        print "Prize of the car=",self.prize
C1=Car("Maruti",2004,200000)
C2=Car("Ford",2014,5000000)
C1.cost()
C2.cost()
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):
        self.name=name
        self.rno=rno
    def dataprint(self):
        print "Name=",self.name
        print "Rno=",self.rno
s1=Student("devi",101)
s2=Student("anjana",102)
s1.dataprint()
s2.dataprint()
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):
        self.name=name
        self.age=age
        self.salary=salary
    def display(self):
        print "Name=",self.name
        print "Age=",self.age
        print "Salary=",self.salary
s1=Person("devi",30,10100)
s2=Person("anjana",35,10200)
s1.display()
s2.display()
Define a class Mobile to store the details of a Mobile (company, model,price) with the following methods.
 a) set_details()- to set the values to the data attributes
 b)display_details()-to display the data attribute values

Create an object of the class and invoke methods. ( university question)
class Mobile:
    def set_details(self):
        self.company=raw_input("enter compnay name...")
        self.model=raw_input("enter model name..")
        self.price=input("enter price..")
    def display_details(self):
        print "Company Name=",self.company
        print "Model=",self.model
        print "Price=",self.price
M=Mobile()
M.set_details()
M.display_details();
Define a class in Python to store the details of students( rollno, mark1,mark2) with the following methods
readData()- to assign values to class attributes
computeTotal()-to find the total marks
printDetails()- to print the attribute values and total marks.
Create an object of this class and invoke the methods. ( Univesrsity question)
class Student:
    def readData(self):
        self.rollno=input("enter roll number...")
        self.mark1=input("enter mark1..")
        self.mark2=input("enter mark2..")
    def computeTotal(self):
        self.total=self.mark1+self.mark2
    def printDetails(self):
        print "roll number-->",self.rollno
        print "Mark1-------->",self.mark1
        print "Mark2-------->",self.mark2
        print "Total Marks---",self.total
S=Student()
S.readData()
S.computeTotal()
S.printDetails()
Define a class in Python to store the details of book( title,author,cost) with the following methodsget_details()- to assign values to class attributes
print_details()- to display the attribute values
Create an object of this class and invoke the methods. ( University question)
class Book:
    def get_details(self):
        self.title=raw_input("enter book title...")
        self.auth=raw_input("enter author..")
        self.cost=input("enter cost..")
    def print_details(self):
        print "Book Tile-->",self.title
        print "Author-------->",self.auth
        print "Cost-------->",self.cost
B=Book()
B.get_details()
B.print_details()
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.
6.Define a class Mobile to store the details of a Mobile (company, model,price) with the following methods.
 a) set_details()- to set the values to the data attributes
 b)display_details()-to display the data attribute values
Create an object of the class and invoke methods. ( university question)
7.Define a class in Python to store the details of students( rollno, mark1,mark2) with the following methods
readData()- to assign values to class attributes
computeTotal()-to find the total marks
printDetails()- to print the attribute values and total marks.
Create an object of this class and invoke the methods. ( Univesrsity question)
8.Define a class in Python to store the details of book( title,author,cost) with the following methods
get_details()- to assign values to class attributes

print_details()- to display the attribute values
Create an object of this class and invoke the methods. ( University question)

Comments

  1. I am really thankful for posting such useful information. It really made me understand lot of important concepts in the topic. Keep up the good work!
    Oracle Training in Chennai | Oracle Course in Chennai

    ReplyDelete
  2. Thank you for an additional great post. Exactly where else could anybody get that kind of facts in this kind of a ideal way of writing? I have a presentation next week, and I’m around the appear for this kind of data.

    Python Training in Chennai

    ReplyDelete
  3. Nice to see this BLOG..keep updating More infromation Digital Lync offers one of the best Full Stack training in Hyderabad with a comprehensive course curriculum with Continuous Integration, Delivery, and Testing. Elevate your practical knowledge with quizzes, assignments, Competitions, and Hackathons to give a boost to your confidence with our hands-on Full Stack Training.
    Python courses
    python Training in Hyderabad
    Python courses in hyderabad
    web development courses
    front end developer course
    full stack developer course with placement

    ReplyDelete
  4. Thanks for sharing this great article. we are provided a Python Web developing services in India And UK.

    ReplyDelete
  5. This is most informative and also this post most user friendly and super navigation to all posts.
    Best Python Online Training in Pune, Mumbai, Delhi NCR

    ReplyDelete




  6. Digital Lync offers one of the best Online Courses Hyderabad with a comprehensive course curriculum with Continuous Integration, Delivery, and Testing. Elevate your practical knowledge with quizzes, assignments, Competitions, and Hackathons to give a boost to your confidence with our hands-on Full Stack Training. An advantage of the online Cources development course in Hyderabad from Digital Lync is to get industry-ready with Career Guidance and Interview preparation.
    DevOps Training Institute
    Python Training Institute
    AWS Training Institute
    Online Full Stack Developer Course Hyderabad
    Online Python Course Hyderabad
    Online AWS Training Course Hyderabad
    Online Devops Course Hyderabad

    ReplyDelete
  7. I like your post very much. It is very much useful for my research. I hope you to share more info about this. Keep posting!! Thanks for sharing your blog is awesome.I gathered lots of information from this blog.
    Salesforce Training in Chennai

    Salesforce Online Training in Chennai

    Salesforce Training in Bangalore

    Salesforce Training in Hyderabad

    Salesforce training in ameerpet

    Salesforce Training in Pune

    Salesforce Online Training

    Salesforce Training

    ReplyDelete
  8. Good to see such a nice Blog Posts "https://www.kloudportal.com/digital-marketing-agency-in-hyderabad/" Best Digital Marketing Agency in Hyderabad

    ReplyDelete
  9. Thank you for this Nice information

    ReplyDelete
  10. Good to see such a nice Information

    ReplyDelete
  11. Thanks you and excellent and good to see the best software training courses for freshers and experience candidates to upgade the next level in an Software Industries Technologies,

    Python Course in Bangalore
    Python Training in Bangalore
    Python Course Bangalore
    Python Training Bangalore

    ReplyDelete
  12. Thanks for sharing such informative blog.
    Become a Data Science expert with us. study Data Science Course in Hyderabad with Innomatics where you get a great experience and better knowledge.

    ReplyDelete
  13. AI Patasala Python Course in Hyderabad is sure to be the ideal choice for those looking to gain insight into all the real-world challenges in this field. AI Patasala Python course is the best option for students to begin their career with the latest technology.
    Online Python Course in Hyderabad

    ReplyDelete

  14. Nice Blog. Great to see that you have highlighted the benefits of a CCC Result . will get to know the important factors while running a business and also be able to handle the difficult tasks in their Jobs.

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. I just found this blog and have high hopes for it to continue. I have added to my favorites. python course

    ReplyDelete
  17. Incredibly conventional blog and articles. I am really very happy to visit your blog. Directly I am found which I truly need. please visit our website for more information about facial recognition

    ReplyDelete
  18. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work... programming lab

    ReplyDelete
  19. Thanks for sharing such useful and informative blog.
    Also check, Python Course in Nagpur

    ReplyDelete
  20. informative article , keep posting and intresting to learn python visit python course in pune

    ReplyDelete

Post a Comment

Popular posts from this blog

Identifiers,Variables and Keywords

Identifiers An identifier is a name given to entities like variables,functions,class, functions etc. It helps to differentiate one entity from another. Rules for writing identifiers 1.Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _.  Names like myClass, var_1 and print_this_to_screen, all are valid example. 2.An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name. 3.Keywords cannot be used as identifiers. Eg: global = 1 is invalid 4.We cannot use special symbols like !, @, #, $, % etc. in our identifier. a@=0 is invalid 5.An identifier can be of any length. Things to Remember Python is a case-sensitive language. This means, Variable and variable are not the same. Always give the identifiers a name that makes sense. While c = 10 is a valid name, writing count=10 would make more sense, and it would be easier to figure out what it represents when you look at your code after

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.