130 likes | 353 Views
Programming Languages 2nd edition Tucker and Noonan. Chapter 13 Object-Oriented Programming I am surprised that ancient and Modern writers have not attributed greater importance to the laws of inheritance ... Alexis de Tocqueville. Contents. 13.1 Prelude: Abstract Data Types
E N D
Programming Languages2nd editionTucker and Noonan Chapter 13 Object-Oriented Programming I am surprised that ancient and Modern writers have not attributed greater importance to the laws of inheritance ... Alexis de Tocqueville
Contents 13.1 Prelude: Abstract Data Types 13.2 The Object Model 13.3 Smalltalk 13.4 Java 13.5 Python
13.5 Python • Multiparadigm • Imperative • Object-orientd • Functional • Scripting language • Dynamically typed
General Characteristics • Builtin types: int, float, infinite precision integers, complex numbers, strings, ... • Data structure • Lists: [1, [2, "allen"], "bob", 3.1416] • Hashes: ["Tucker": "Bowdoin", "Noonan": "W&M"] • Tuples: (238111, "allen", "bob") • Strings: viewed as list of characters • List operators work on strings
Python "less forgiving" than Perl • Cannot do string operations on numbers • Or vice versa • Cannot index past end of list • Must append to end of a list
Statements fairly conventional • Indentation used for compound statements • No $var as in Perl (bareword error) • Reference semantics used for assignment • Multiple inheritance • All methods and instance variables are public. • Variables must be set before being referenced. • Run time type identification • Reflection
Examle: Polynomials • Represent Polynomials: 3 x2 + 5x - 7 • Representation: #(-7 5 3) • Subclass of Magnitude
class Polynomial: • def __init__(self, coef): • """constructor""" • self.coefficient = [ ] + coef • def degree(self): • """Highest power with a non-zero coefficient""" • return len(coefficient)
def coefficient(self, power): • """Coefficient of given power""" • if power > len(coefficient): • return 0 • return coefficient[power] • def asList(self): • """return copy of coefficient""" • return [ ] + coefficient
def __eq__(self,aPoly): • """returnself == aPoly""" • returncoefficient == aPoly.asList( ) • def __ne__(self,aPoly): • """returnself <> aPoly.asList( )""" • returncoefficient <> aPoly.asList( )
def __str__(self): • """return string representation""" • r = "" • p = len(coefficient) + 1 • while p > 0: • p = p - 1 • if coefficient[p] == 0: continue • if p < len(coefficient): r = r + "+" • r = r + str(coefficient[p]) • if p == 0: continue • r = r + "x" • if p <= 1: continue