
Exploring Object-Oriented Programming in Python
Delve into the world of object-oriented programming using Python, where you will learn about defining new classes, understanding the distinctions between classes and objects, and the fundamentals of object-oriented design. Explore concepts such as classifying objects, object instantiation, and the syntax of defining classes in Python, with practical examples included throughout.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Introduction to Computing Using Python Object-Oriented Programming Defining new Python Classes Overloaded Operators
Class vs Objects / Instances One objective is to understand the difference between objects and classes Namely: An object is one instance of a class Describe the circles in OO terms:
Classifying objects Although the 3 circles are 3 different objects, they are all members of a class 'Circle' It is also accurate to say that the examples below are 3 "instances" of the class Circle As members of the same class, they have the same descriptive figures Color Radius Center coordinates (x,y)
Object-Oriented Design (OOD) 1. Object combines data and operations into a unit Data: Descriptive attributes Operations: Behaviors A class is a collection of objects that share the same data attributes and behavior e.g. class Circle, class Student, class Car An object refers to a single instance of a class. Here we will instantiate 2 objects of class 'Circle': c1 = Circle() c2 = Circle() Note that we are using the "default constructor" Though all objects of a class share the same data attributes (e.g. color, radius, center), each objects has its own state (i.e. the value of each data attribute). 2. 3. 4.
Class syntax class <Class Name>: <class variable 1> = <value> <class variable 2> = <value> . . . def <class method 1>(self, arg1, arg2, . . .): <implementation of class method 1> def <class method 2>(self, arg1, arg2, . . .): <implementation of class method 2> Usually consists of Variables Methods Note: Recall that class variables are shared among all objects of the class. With instance variables, however, each object has its own copy of that variable. We use instance variables far more frequently than class variables.
Introduction to Computing Using Python A new class: Point Suppose we would like to have a class that we can use to represent points on an x,y plane e.g. for a graphics application Let s first informally describe how we would like to use this class >>> point = Point() >>> point.setx(3) >>> point = Point() >>> point = Point() >>> point.setx(3) >>> point.setx(3) >>> point.sety(4) >>> point.get() >>> point.get() (3, 4) (3, 4) >>> point.move(1, 2) >>> point.get() >>> point = Point() >>> point = Point() >>> point.setx(3) >>> point.setx(3) >>> point.sety(4) >>> point.sety(4) >>> point.get() (3, 4) (3, 4) >>> point.move(1, 2) >>> point.move(1, 2) >>> point.get() (4, 6) (4, 6) >>> point.setx(-1) >>> point = Point() >>> point = Point() >>> point.setx(3) >>> point.sety(4) >>> point.sety(4) >>> point.get() >>> point = Point() >>> >>> point.setx(3) >>> >>> point.sety(4) >>> >>> point.get() (3, 4) >>> >>> point.move(1, 2) >>> >>> point.get() (4, 6) >>> >>> point.setx(-1) >>> >>> point.get() (-1, 6) >>> Usage p.setx(xcoord) Explanation point y Sets the x coordinate of point p to xcoord Sets the y coordinate of point p to ycoord p.sety(ycoord) p.get() x Returns the x and y coordinates of point p as a tuple (x, y) Changes the coordinates of point p from the current (x, y) to (x+dx, y+dy) p.move(dx, dy) How do we create this new class Point?
Introduction to Computing Using Python Review: A class is a namespace >>> list.pop <method 'pop' of 'list' objects> >>> list.sort <method 'sort' of 'list' objects> >>> list.pop <method 'pop' of 'list' objects> >>> list.sort <method 'sort' of 'list' objects> >>> >>> dir(list) ['__add__', '__class__', ... 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] A class is really a namespace A class is really a namespace The name of this namespace is the name of the class The names defined in this namespace are the class attributes (e.g., class methods) methods) The class attributes can be accessed using the standard namespace notation The name of this namespace is the name of the class The names defined in this namespace are the class attributes (e.g., class Function dir() can be used to list the class attributes __add__ x count pop . . . namespace list sort() __add__() count() pop()
Introduction to Computing Using Python >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list.sort(lst) >>> lst [1, 2, 3, 7, 8, 9] >>> >>> lst.append(6) >>> lst [1, 2, 3, 7, 8, 9, 6] >>> >>> list.append(lst, 5) >>> lst [1, 2, 3, 7, 8, 9, 6, 5] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst >>> lst [1, 2, 3, 7, 8, 9] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list.sort(lst) >>> lst >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] [1, 2, 3, 7, 8, 9] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list.sort(lst) >>> lst [1, 2, 3, 7, 8, 9] [1, 2, 3, 7, 8, 9] >>> lst.append(6) >>> lst [1, 2, 3, 7, 8, 9, 6] Review: Class methods A class method is really a function defined in the class namespace; when Python executes lst.sort() lst.append(6) instance.method(arg1, arg2, ) it first translates it to list.sort(lst) list.append(lst, 6) class.method(instance, arg1, arg2, ) and actually executes this last statement The function has an extra argument, which is the object invoking the method __add__ x count pop . . . namespace list sort() __add__() count() pop()
Introduction to Computing Using Python Developing the class Point Usage p.setx(xcoord) Explanation Sets the x coordinate of point p to xcoord Sets the y coordinate of point p to ycoord A namespace called Point needs to be defined p.sety(ycoord) Namespace Point will store the names of the 4 methods (the class attributes) p.get() Returns the x and y coordinates of point p as a tuple (x, y) Changes the coordinates of point p from the current (x, y) to (x+dx, y+dy) p.move(dx, dy) setx sety get move . . . namespace Point move() setx() sety() get()
Introduction to Computing Using Python Defining the class Point Usage p.setx(xcoord) setx(p, xcoord) Sets the x coordinate of point p to xcoord sety(p, ycoord) Sets the y coordinate of point p to ycoord get(p) Returns the x and y coordinates of point p as a tuple (x, y) move(p, dx, dy) Changes the coordinates of point p from the current (x, y) to (x+dx, y+dy) >>> Point.get(point) (-1, 6) >>> Point.setx(point, 0) >>> Point.get(point) (0, 6) >>> Point.sety(point, 0) >>> Point.get(point) (0, 0) >>> Point.move(point, 2, -2) >>> Point.get(point) (2, -2) Usage Explanation Sets the x coordinate of point p to xcoord Sets the y coordinate of point p to ycoord Explanation A namespace called Point needs to be defined p.sety(ycoord) Namespace Point will store the names of the 4 methods (the class attributes) p.get() Returns the x and y coordinates of point p as a tuple (x, y) Changes the coordinates of point p from the current (x, y) to (x+dx, y+dy) p.move(dx, dy) Each method is a function that has an extra (first) argument which refers to the object that the method is invoked on
Introduction to Computing Using Python Defining the class Point variable that refers to the object on which the method is invoked class Point: 'class that represents a point in the plane' A namespace called Point needs to be defined def setx(self, xcoord): 'set x coordinate of point to xcoord' # to be implemented Namespace Point will store the names of the 4 methods (the class attributes) def sety(self, ycoord): 'set y coordinate of point to ycoord' # to be implemented def get(self): 'return coordinates of the point as a tuple' # to be implemented Each method is a function that has an extra (first) argument which refers to the object that the method is invoked on def move(self, dx, dy): 'change the x and y coordinates by dx and dy' # to be implemented IMP: By convention, we call this parameter "self". The Python class statement defines a new class (and associated namespace)
Introduction to Computing Using Python The object namespace class Point: 'class that represents a point in the plane' 'class that represents a point in the plane' class Point: We know that a namespace is associated with every class def setx(self, xcoord): 'set x coordinate of point to xcoord' # to be implemented self.x = xcoord def setx(self, xcoord): 'set x coordinate of point to xcoord' A namespace is also associated with every object def sety(self, ycoord): 'set y coordinate of point to ycoord' # to be implemented # to be implemented def sety(self, ycoord): 'set y coordinate of point to ycoord' >>> point = Point() >>> >>> point.x = 3 >>> >>> >>> point = Point() >>> point = Point() >>> point = Point() >>> >>> Point.setx(point, 3) def get(self): 'return coordinates of the point as a tuple' def get(self): 'return coordinates of the point as a tuple' # to be implemented # to be implemented x def move(self, dx, dy): 'change the x and y coordinates by dx and dy' # to be implemented # to be implemented def move(self, dx, dy): 'change the x and y coordinates by dx and dy' namespace point The Python class statement defines a new class 3
Introduction to Computing Using Python Defining the class Point class Point: 'class that represents a point in the plane' A namespace called Point needs to be defined def setx(self, xcoord): 'set x coordinate of point to xcoord' self.x = xcoord Namespace Point will store the names of the 4 methods (the class attributes) def sety(self, ycoord): 'set y coordinate of point to ycoord' self.y = ycoord def get(self): 'return coordinates of the point as a tuple' return (self.x, self.y) Each method is a function that has an extra (first) argument which refers to the object that the method is invoked on def move(self, dx, dy): 'change the x and y coordinates by dx and dy' self.x += dx self.y += dy
Introduction to Computing Using Python Exercise class Point: 'class that represents a point in the plane' 'class that represents a point in the plane' class Point: Add new method getx() to class Point def setx(self, xcoord): 'set x coordinate of point to xcoord' self.x = xcoord self.x = xcoord def setx(self, xcoord): 'set x coordinate of point to xcoord' >>> point = Point() >>> point.setx(3) >>> point.getx() 3 def sety(self, ycoord): 'set y coordinate of point to ycoord' self.y = ycoord self.y = ycoord def sety(self, ycoord): 'set y coordinate of point to ycoord' def get(self): 'return coordinates of the point as a tuple' return (self.x, self.y) return (self.x, self.y) def get(self): 'return coordinates of the point as a tuple' def move(self, dx, dy): 'change the x and y coordinates by dx and dy' self.x += dx self.y += dy self.y += dy def move(self, dx, dy): 'change the x and y coordinates by dx and dy' self.x += dx def getx(self): 'return x coordinate of the point' return self.x
Introduction to Computing Using Python The instance namespaces Variables stored in the namespace of an object (instance) i.e. as opposed to the class namespace -- are called instance variables (or instance attributes) Every object will have its own namespace and therefore its own instance variables >>> a = Point() >>> a.setx(3) >>> a.sety(4) >>> a.sety(4) >>> b = Point() >>> b.setx(0) >>> b.sety(0) >>> b.sety(0) >>> a.get() (3, 4) >>> b.get() (0, 0) >>> a = Point() >>> a.setx(3) >>> a.setx(3) >>> a.sety(4) >>> b = Point() >>> b.setx(0) >>> a = Point() >>> >>> a = Point() >>> a.setx(3) >>> a.sety(4) >>> >>> b = Point() >>> b.setx(0) >>> b.sety(0) >>> >>> a.get() (3, 4) >>> b.get() (0, 0) >>> >>> a.x 3 >>> b.x 0 >>> x y x y object a object b 3 4 0 0
Introduction to Computing Using Python The class and instance attributes Method names setx, sety, get, and move are defined in namespace Point not in namespace p1 or p2. setx sety get move . . . namespace Point . . . Python does the following when evaluating expression p1.setx: x y x y 1. It first attempts to find name setx in the object s namespace i.e. p1 . object p1 object p2 3 4 0 0 2. If name setx does not exist in namespace p1, then it attempts to find setx in the class namespace (i.e. Point)
Introduction to Computing Using Python General format for defining a class: class <Class Name>: <class variable 1> = <value> <class variable 2> = <value> ... def <class method 1>(self, arg11, arg12, ...): <implementation of class method 1> def sety(self, ycoord): self.y = ycoord class Point: def setx(self, xcoord): self.x = xcoord def <class method 2>(self, arg21, arg22, ...): <implementation of class method 2> def get(self): return (self.x, self.y) ... def move(self, dx, dy): self.x += dx self.y += dy Note: This class has no documentation - Missing / poor documentation makes collaborators, partners, hiring-managerssad
Introduction to Computing Using Python Why docstrings are important >>> help(Point) Help on class Point in module __main__: class Point(builtins.object) | Methods defined here: | | get(self) | | move(self, dx, dy) | | setx(self, xcoord) | | sety(self, ycoord) | | --------------------------------------------------------------------- - | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) Consider the situation where the programmer did not include any docstrings: In that situation, typing: help(Point) would yield the output shown here.
Introduction to Computing Using Python Let s add documentation: class Point: 'class that represents a point in the plane' def setx(self, xcoord): 'set x coordinate of point to xcoord' self.x = xcoord def sety(self, ycoord): 'set y coordinate of point to ycoord' self.y = ycoord def get(self): 'return coordinates of the point as a tuple' return (self.x, self.y) def move(self, dx, dy): 'change the x and y coordinates by dx and dy' self.x += dx self.y += dy
Introduction to Computing Using Python Now compare with a class that includes docstrings: In this situation, typing: help(Point) is actually helpful! With docstrings: >>> help(Point) Help on class Point in module __main__: class Point(builtins.object) | class that represents a point in the plane | | Methods defined here: | | get(self) | return a tuple with x and y coordinates of the point | | move(self, dx, dy) | change the x and y coordinates by dx and dy | | setx(self, xcoord) | set x coordinate of point to xcoord | | sety(self, ycoord) | set y coordinate of point to ycoord | | --------------------------------------------------------------------- - | Data descriptors defined here: ...
Introduction to Computing Using Python Creating constructors This __init__() method is automatically invoked by interpreter every single time a Point object is created At the moment, It takes three steps to create a Point object that contains specific x and y coordinates class Point: 'class that represents a point in the plane 'class that represents a point in the plane class Point: def setx(self, xcoord): 'set x coordinate of point to xcoord' self.x = xcoord self.x = xcoord self.y = ycoord def __init__(self, xcoord, ycoord): 'initialize coordinates to (xcoord, ycoord)' >>> a = Point() >>> a.setx(3) >>> a.sety(4) >>> a.get() (3, 4) >>> def sety(self, ycoord): 'set y coordinate of point to ycoord' self.y = ycoord 'set x coordinate of point to xcoord' self.x = xcoord Wouldn t it be nice if we could do it in one step? def setx(self, xcoord): def get(self): 'return coordinates of the point as a tuple' return (self.x, self.y) 'set y coordinate of point to ycoord' self.y = ycoord def sety(self, ycoord): >>> a = Point(3, 4) >>> a.get() (3, 4) >>> def move(self, dx, dy): 'change the x and y coordinates by dx and dy' self.x += dx self.y += dy return (self.x, self.y) def get(self): 'return coordinates of the point as a tuple' >>> p1 = Point(4, 7) >>> p2 = Point(-2, 4) >>> p3 = Point(14, 6) >>> p4 = Point(-2, -3) def move(self, dx, dy): 'change the x and y coordinates by dx and dy' self.x += dx self.y += dy
Introduction to Computing Using Python Default constructor xcoord is set to 0 if the argument is missing ycoord is set to 0 if the argument is missing class Point: class Point: 'class that represents a point in the plane 'class that represents a point in the plane Problem: Now we can t create an uninitialized point def __init__(self, xcoord=0, ycoord=0): 'initialize coordinates to (xcoord, ycoord)' self.x = xcoord def __init__(self, xcoord, ycoord): 'initialize coordinates to (xcoord, ycoord)' self.x = xcoord self.y = ycoord self.y = ycoord Built-in types support default constructors def setx(self, xcoord): 'set x coordinate of point to xcoord' self.x = xcoord self.x = xcoord def setx(self, xcoord): 'set x coordinate of point to xcoord' >>> a = Point() Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> a = Point() TypeError: __init__() takes exactly 3 arguments (1 given) >>> Want to augment class Point so it supports a default constructor def sety(self, ycoord): 'set y coordinate of point to ycoord' self.y = ycoord self.y = ycoord def sety(self, ycoord): 'set y coordinate of point to ycoord' def get(self): 'return coordinates of the point as a tuple' return (self.x, self.y) return (self.x, self.y) def get(self): 'return coordinates of the point as a tuple' >>> a = Point() >>> a.get() (0, 0) >>> >>> n = int(3) >>> n 3 >>> n = int() >>> n 0 >>> def move(self, dx, dy): 'change the x and y coordinates by dx and dy' self.x += dx self.y += dy self.y += dy def move(self, dx, dy): 'change the x and y coordinates by dx and dy' self.x += dx
Introduction to Computing Using Python Exercise Develop class Animal that supports methods: setSpecies(species) setLanguage(language) speak() >>> snoopy = Animal() >>> snoopy.setpecies('dog') >>> snoopy.setLanguage('bark') >>> snoopy.speak() I am a dog and I bark. class Animal: 'represents an animal' def setSpecies(self, species): 'sets the animal species' self.spec = species def setLanguage(self, language): 'sets the animal language' self.lang = language def speak(self): 'prints a sentence by the animal' print('I am a {} and I {}.'.format(self.spec, self.lang))