Python Programming - VII. Customizing Classes and Operator Overloading

50 %
50 %
Information about Python Programming - VII. Customizing Classes and Operator Overloading
Technology

Published on January 18, 2014

Author: ranelpadon

Source: slideshare.net

SEQUENCE OVERLOADING However, too much overloading may also backfire.  VII. CUSTOMIZING CLASSES PYTHON PROGRAMMING Engr. Ranel O. Padon

PYTHON PROGRAMMING TOPICS I •Introduction to Python Programming II •Python Basics III •Controlling the Program Flow IV •Program Components: Functions, Classes, Packages, and Modules V •Sequences (List and Tuples), and Dictionaries VI •Object-Based Programming: Classes and Objects VII •Customizing Classes and Operator Overloading VIII •Object-Oriented Programming: Inheritance and Polymorphism IX •Randomization Algorithms X •Exception Handling and Assertions XI •String Manipulation and Regular Expressions XII •File Handling and Processing XIII •GUI Programming Using Tkinter 2

INTRODUCTION Customization provides solutions for various needs.

INTRODUCTION Customization has pros and cons.

INTRODUCTION Special Methods: __init__ and __del__ __init__ creates objects __del__ destroys objects 5

INTRODUCTION The typical method-call notation is cumbersome for mathematical classes. >> polynomial1.add(polynomial2) better or more natural way: >> polynomial1 + polynomial2 This is called Operator Overloading. 6

INTRODUCTION For faster development, reuse, modify, or extend the built-in attributes, methods & operators of a Class. 7

INTRODUCTION Python enables the programmer to overload most operators to be sensitive to the context in which they are used. >> print 2 + 3 >> print “Mang” + “Jose” >> print 2 * 3 >> print “Mang” * 2 #prints “MangMang” 8

INTRODUCTION The interpreter takes the appropriate action based on the manner in which the operator is used. 9

INTRODUCTION Some operators are overloaded frequently, especially operators like + and —. The job performed by overloaded operators also can be performed by explicit method calls, but operator notation is often clearer. 10

STRING REPRESENTATION A Python class can define special method __str__, to provide an informal (i.e., human-readable) string representation of an object of the class. __str__ is analogous to Java’s toString() method. 11

STRING REPRESENTATION If a client program of the class contains the statement print objectOfClass Python calls the object’s __str__ method and outputs the string returned by that method. 12

STRING REPRESENTATION The raw face of an object. 13

STRING REPRESENTATION default invocation >> print halimawSaBanga __main__.HalimawSaBanga instance at 0x0204E120 if __str__ is overriden >> print halimawSaBanga 500-year-old na Halimaw natagpuan sa banga! 14

The Raw Faces of an Object The __str__ Faces of an Object 15

STRING REPRESENTATION 16

STRING REPRESENTATION 17

ATTRIBUTE ACCESS 18

ATTRIBUTE ACCESS 19

ATTRIBUTE ACCESS 20

ATTRIBUTE ACCESS 21

ATTRIBUTE ACCESS 22

ATTRIBUTE ACCESS 23

OPERATOR OVERLOADING Python does not allow new operators to be created, it does allow most existing operators to be overloaded when these operators are used with objects of a programmer-defined type, the operators have meaning appropriate to the new types. 24

Overloading: It’s about maximizing capabilities.

OPERATOR OVERLOADING overloading contributes to the extensibility of Python language 26

OPERATOR OVERLOADING Restrictions 1. precedence cannot be changed 2. arity cannot be changed (i.e., unary to binary) 27

OPERATOR OVERLOADING Restrictions 28

OPERATOR OVERLOADING Unary A unary operator for a class is overloaded as a method that takes only the object reference argument (self ) 29

OPERATOR OVERLOADING Unary 30

OPERATOR OVERLOADING Binary A binary operator or statement for a class is overloaded as a method with two arguments: self and other. 31

OPERATOR OVERLOADING Rational A Rational number is a fraction represented as a numerator (top) and a denominator (bottom). A rational number can be positive, negative or zero. Class Rational’s interface includes a default constructor, string representation method, overloaded abs function, equality operators and several mathematical operators. 32

OPERATOR OVERLOADING Rational 33

OPERATOR OVERLOADING Binary When overloading binary operator +, if y and z are objects of class Rational, then y + z is treated as if y.__add__(z) had been written, invoking the __add__ method. 34

OPERATOR OVERLOADING Binary Usually, overloaded binary operator methods create and return new objects of their corresponding class. 36

OPERATOR OVERLOADING Binary What happens if we evaluate the expression y + z or the statement y += z, and only y is an object of class Rational? In both cases, z must be coerced (i.e., converted) to an object of class Rational, before the appropriate operator overloading method executes. 37

OPERATOR OVERLOADING Binary 38

OPERATOR OVERLOADING Binary 39

OPERATOR OVERLOADING Built-ins A class also may define special methods that execute when certain built-in functions are called on an object of the class. For example, we may define special method __abs__ for class Rational, to execute when a program calls abs(rationalObject) to compute the absolute value of an object of that class. 40

OPERATOR OVERLOADING Built-ins 41

TYPE CONVERSION Sometimes all the operations “stay within a type.” For example, adding (concatenating) a string to a string produces a string. But, it is often necessary to convert or coerce data of one type to data of another type. 42

TYPE CONVERSION Programmers can force conversions among built-in types by calling the appropriate Python function, such as int or float. 43

TYPE CONVERSION But what about user-defined classes? The interpreter cannot know how to convert among userdefined classes and built-in types. 44

TYPE CONVERSION The programmer must specify how such conversions are to occur with special methods that override the appropriate Python functions. 45

TYPE CONVERSION For example, a class can define special method __int__ that overloads the behavior of the call int( anObject ) to return an integer representation of the object. 46

TYPE CONVERSION 47

TYPE CONVERSION 48

CASE STUDY: RATIONAL CLASS Sample computations with Rational objects: 49

CASE STUDY: RATIONAL CLASS function gcd() computes the greatest common divisor of two values. Class Rational uses this function to simplify the rational number. 50

CASE STUDY: RATIONAL CLASS 51

CASE STUDY: RATIONAL CLASS 52

CASE STUDY: RATIONAL CLASS 53

CASE STUDY: RATIONAL CLASS 54

CASE STUDY: RATIONAL CLASS 55

CASE STUDY: RATIONAL CLASS 56

CASE STUDY: RATIONAL CLASS 57

CASE STUDY: RATIONAL CLASS 58

CASE STUDY: RATIONAL CLASS 59

CASE STUDY: RATIONAL CLASS 60

CASE STUDY: RATIONAL CLASS 61

CASE STUDY: RATIONAL CLASS 62

CASE STUDY: RATIONAL CLASS 63

CASE STUDY: RATIONAL CLASS 64

CASE STUDY: RATIONAL CLASS 65

CASE STUDY: RATIONAL CLASS 66

CASE STUDY: RATIONAL CLASS 67

END NOTES Overloading is a powerful concept. It allows the programmer to reuse/modify existing concepts and operations. 68

…and enables the customization of classes. SEQUENCE OVERLOADING

SEQUENCE OVERLOADING However, too much overloading may also backfire. 

REFERENCES  Deitel, Deitel, Liperi, and Wiedermann - Python: How to Program (2001).  Disclaimer: Most of the images/information used here have no proper source citation, and I do not claim ownership of these either. I don’t want to reinvent the wheel, and I just want to reuse and reintegrate materials that I think are useful or cool, then present them in another light, form, or perspective. Moreover, the images/information here are mainly used for illustration/educational purposes only, in the spirit of openness of data, spreading light, and empowering people with knowledge.  71

#prints presentations

Add a comment

Related presentations

Related pages

Python Programming - VII. Customizing Classes and Operator ...

1. SEQUENCE OVERLOADING However, too much overloading may also backfire. VII. CUSTOMIZING CLASSESPYTHON PROGRAMMINGEngr. Ranel O. Padon. 2. PYTHON ...
Read more

Python Programming - VI. Classes and Objects - Technology

PYTHON PROGRAMMING TOPICS I•Introduction to Python ProgrammingII ... Classes and ObjectsVII•Customizing Classes and Operator OverloadingVIII ...
Read more

Training Course: Introduction to Python Programming ...

Introduction to Python Programming course. ... Classes Can Intercept Python Operators ... Operator Overloading Step 4: Customizing Behavior by Subclassing
Read more

pythonprogramming-xiii-140310110600-phpapp01.pdf - Engr ...

python programming topics ...
Read more

Fluent Python : [clear, concise, and effective programming]

TableofContents | vii. ... ProvideAggregateClassestoUsers 364 8. ... OperatorOverloading 101 376 UnaryOperators 376 Overloading
Read more

Classes Can Intercept Python Operators - Learning Python ...

Classes Can Intercept Python Operators Let’s move on to the third and final major difference between classes and modules: operator overloading ...
Read more

29. Operator Overloading - Learning Python, 4th Edition [Book]

We looked briefly at operator overloading in prior chapters; here, we’ll ... You are previewing Learning Python, 4th Edition ... Designing with Classes.
Read more

Learning Python, 5th Edition - O'Reilly Media

Dive into classes: Python’s object ... This book is very suitable for people new to programming as ... Comments about oreilly Learning Python, ...
Read more