IIITD Classes and Objects Objects Everything in Python
IIITD Classes and Objects
Objects Everything in Python is an object. For example, when we do the assignment a = 2, here 2 is an object stored in memory and a is the name we associate it with. >>> a = 2 >>> id(2) 507098816 >>> id(a) 507098816
>>> a = 2 >>> id(a) 507098816 >>> a = a+1 >>> id(a) 507098848 >>> id(3) 507098848 >>> b = 2 >>> id(b) 507098816
Classes and Objects Python is an object oriented programming language. Unlike procedure oriented programming, in which the main emphasis is on functions, object oriented programming stress on objects. Object is simply a collection of data (variables) and methods (functions) that act on those data.
Contd. . Class is a blueprint for the object. Class like a sketch (prototype) of a house. It contains all the details about the floors, doors, windows House is the object As, many houses can be made from a description, we can create many objects from a class.
We want to store details of 5 employees Use a list with employee names , Age, Salary etc. . How about if I use a class Employee with three members- Name, Age and Salary Create multiple Employee objects
A class is something that just contains structure — it defines how something should be laid out or structured, but doesn’t actually fill in the content. This is where objects come in. An object is a specific copy of the class that does contain all of the content
Example of class with attributes. Every time I am assigning the value to each object Can I design a function which takes an object as an argument and assigns the values. Yes its def __init__(self, x=0, y=0):
Example/Usage of Classes and Objects
class Point: """ Point class represents and manipulates x, y coords. """ def __init__(self, x=0, y=0): """ Create a new point at x, y ""“ self. x = x self. y = y
>>> p = Point(4, 2) >>> q = Point(6, 3) >>> r = Point() # r represents the origin (0, 0) >>> print(p. x, q. y, r. x) 4 3 0
- Slides: 12