COP 3223H meeting -*- Outline -*- * object-oriented classes background This is background for representing recursive data in Python, as in grammars and abstract syntax trees. ** classes define how objects are produced and behave This is a very simple class Classes produce objects like factories produce, say, sunglasses Point out each kind of method ------------------------------------------ PYTHON CLASSES DEFINE OBJECTS class Cell(object): def __init__(self, value): """Initialize this cell with the given value.""" def value(self): """Return the value in this cell.""" def set(self, value): """Change the value in this cell to be the given value.""" def __repr__(self): """Return a string representation of this cell.""" def __str__(self): """Return a string showing the value in this cell.""" ------------------------------------------ Note that object is the superclass of Cell, from which it inherits behavior Thus Cell is a subclass of object, and we also say that Cell is a subtype of object. ... self.val = value ... return self.val ... self.val = value ... return "Cell(" + repr(self.value()) + ")" ... return "Cell(" + str(self.value()) + ")" Point out that repr(o) calls o.__repr__() and str(o) calls o.__str__() ** object construction ------------------------------------------ OBJECT CONSTRUCTION Objects are constructed by calling the class name as a function, Example: c1 = Cell(1) c2 = Cell(2) ------------------------------------------ ... passing it the arguments from the __init__() method, other than self ** method calls ------------------------------------------ METHOD CALLS Functions in a class that have a self argument are called Method calls are written: e.m(args) for example: c1.value() c2.set(3) ------------------------------------------ ... methods ... where the value of e is the receiver, passed as self and args are the other arguments of the method (not self)