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
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.
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()
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 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()
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)
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)
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!
ReplyDeleteOracle Training in Chennai | Oracle Course in Chennai
Good Post. I like your blog. Thanks for Sharing
ReplyDeletePython Course in Noida
Thank you for sharing your thoughts and knowledge on this topic.
ReplyDeletePython Institute in Hyderabad
Python Course in Hyderabad
Wonderful Blog and a good way to present it. Knowledge also great. If you want more information thenn visit here:-
ReplyDeleteDigital marketing course
Android Course
Data Science Course
Ethical Hacking Course
NIOS
Python Class
graphic and web design courses
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.
ReplyDeletePython Training in Chennai
Thank you for sharing wonderful information with us to get some idea about that content.
ReplyDeletePython Flask Training in Ameerpet
Python Flask Training in Hyderabad
Python Flask Online Training
Flask Framework Training
Python Flask Training
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.
ReplyDeletePython courses
python Training in Hyderabad
Python courses in hyderabad
web development courses
front end developer course
full stack developer course with placement
Thanks for sharing this great article. we are provided a Python Web developing services in India And UK.
ReplyDelete
ReplyDeleteThis is an amazing blog, thank you so much for sharing such valuable information with us.
Python Course in Hyderabad
Python Institute in Hyderabad
Python Online Training in Hyderabad
Python Training in Hyderabad
Python Training
Python Online Training
This is most informative and also this post most user friendly and super navigation to all posts.
ReplyDeleteBest Python Online Training in Pune, Mumbai, Delhi NCR
ReplyDeleteDigital 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
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.
ReplyDeleteSalesforce 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
Here is the site(bcomexamresult.in) where you get all Bcom Exam Results. This site helps to clear your all query.
ReplyDeleteJMIU BCOM 3rd Year Result 2020
BA 3rd year Result 2019-20
Sdsuv University B.COM 3rd/HONOURS Sem Exam Result 2018-2021
Good to see such a nice Blog Posts "https://www.kloudportal.com/digital-marketing-agency-in-hyderabad/" Best Digital Marketing Agency in Hyderabad
ReplyDeleteThank you for this Nice information
ReplyDeleteGood to see such a nice Information
ReplyDeletehelpful article
ReplyDeleteclick here
Thank you for this Nice information
ReplyDeletePython Online Training In Hyderabad
Python Online Training
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,
ReplyDeletePython Course in Bangalore
Python Training in Bangalore
Python Course Bangalore
Python Training Bangalore
Thanks for sharing such informative blog.
ReplyDeleteBecome a Data Science expert with us. study Data Science Course in Hyderabad with Innomatics where you get a great experience and better knowledge.
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.
ReplyDeleteOnline Python Course in Hyderabad
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.
Nice blog Thanks for sharing
ReplyDeletePython developer job available in Chennai
This comment has been removed by the author.
ReplyDeleteWonderful post and more informative!keep sharing Like this!
ReplyDeleteBenefits of RPA for Modern Businesses
Advantages of RPA for Modern Businesses
I just found this blog and have high hopes for it to continue. I have added to my favorites. python course
ReplyDeleteIncredibly 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
ReplyDeletePerfect
ReplyDeleteI 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
ReplyDeleteThanks for posting this information.
ReplyDeletePython Online Classes
Best Python Online Training
Thanks for sharing such useful and informative blog.
ReplyDeleteAlso check, Python Course in Nagpur
informative article , keep posting and intresting to learn python visit python course in pune
ReplyDeleteI recently came across an incredible Python Full Stack course in Ameerpet and I just had to share my experience. This course is a game-changer for anyone looking to dive into both front-end and back-end development using Python
ReplyDeleteThank you for another amazing post! The way you present the information is so clear and well-structured. I have a presentation coming up next week, and this is exactly the kind of content I’ve been searching for. Where else can I find more resources like this? Keep up the great work! https://vataliya-soft-tech.blogspot.com/2024/09/c-programming-class-in-vadodara-gujarat.html, https://vataliyacomputerclasses.wordpress.com/2024/09/22/python-programing-in-vadodara-gujarat/
ReplyDelete