Download presentation
Presentation is loading. Please wait.
Published byTodd Greene Modified over 9 years ago
1
Chapter 10 Classes
2
Review of basic OOP concepts Objects: comprised of associated DATA and ACTIONS (methods) which manipulate that data. Instance: a unique actual object Instance variables: the actual values associated with an object Attributes: data (instance variables) + methods of an object Class: every object is an instance of a parent class. Constructor: the code by which an instance is created from a parent class
3
Why a Class? Simplifies variables Associates methods and data in an intuitive structure Modularizes code Portability: Classes can be imported to other programs Reusability Models reality Reduces error because methods and variables are written once, used often
4
Constructing a Class: header Definition header for a class is class identifier: Keyword is class; class elements are signaled with a colon, and demarcated by indentation (off-side rule)
5
Constructing a Class: adding methods (functions) Methods defined in a class always take one formal parameter: self But just like functions, methods associated with a class can have multiple parameters and multiple return values. Example of a method with 2 parameters: def getValue(self): return self.value Example of a method with a return value: def setValue(self, value): self.value = value
6
class BeerCan: def __init__(self, ounces, brand, temp) self.ounces = ounces self.brand = brand self.temp = temp def getOunces(self): return self.ounces def drink(self): self.ounces = self.ounces -1 def spillBeer(self): self.ounces = 0
7
Constructing a Class: adding properties (data or values) Properties, or data, or instance variables, are defined in the method which constructs instances of the class. This is the __init__() method. In this initializing method you can set literal default values for instance variables associated with the class or you can create instance variables by accepting a value delivered as a parameter at the time the instance of the class was constructed.
8
def __init__(self, ounces, brand, temp) self.ounces = ounces self.brand = brand self.temp = temp These three values are filled by passed parameters, not by the programmer per se. So, when we construct an instance of the BeerCan variable, we have to provide those values: myBeer = BeerCan(12, “Heineken”, “lukewarm”)
9
The multi-sided die example # msdie.py from random import randrange class MSDie: def __init__(self, sides): self.sides = sides self.value = 1 def roll(self): self.value = randrange(1, self.sides+1) def getValue(self): return self.value def setValue(self, value): self.value = value
10
About the self parameter Every method associated with a class must have, in Python, an initial parameter which refers to the object class itself. In both the BeerCan class and the MSdie class, all methods have the self parameter. But when those methods are invoked, that parameter is never referred to between parentheses. Instead, the name of the instance/constructed object is referenced before the method name, separated with a dot separator.
11
In our BeerCan class definition, we defined one method: def getOunces(self): return self.ounces When we invoke this method, the self parameter becomes the object reference; no other parameters are required. print myBeer.getOunces() The self paramter Self parameter becomes object reference No other actual parameters needed
12
The BeerCan __init__ method The first method defined in any class is always the __init__ method. This is the method which by default constructs instances/objects of the class myBeer = BeerCan(12, “Heineken”, “lukewarm”) The __init__() method in the BeerCan class creates three properties or data fields: def __init__(self, ounces, brand, temp) self.ounces = ounces self.brand = brand self.temp = temp This constructor invokes the __init__() method
13
The __init__() method in the MSdie class creates just two properties, and sets one to a literal (hard-coded) value and sets the other to a value passed by parameter when the object is constructed from the Msdie class. class MSDie: def __init__(self, sides): self.sides = sides self.value = 1
14
One of the most common and sensible uses of classes and objects is to create records, that is, classes which represent people’s activities and identities. Clients, employees, students, customers, patients, etc., all represent people interacting with some social institution. Classes and objects are great at associating a variety of different kinds of data, just like people’s activities and identities are comprised of different dimensions. class Student: def __init__(self, name, hours, qpoints): self.name = name self.hours = float(hours) self.qpoints = qpoints
15
Workshop Create a Customer object which serves as a record for your online shop, in command line mode. Include all contact information plus data fields for names of product ordered and quantities ordered. Include methods for reversing the name and calculating a subtotal.
16
Separation of concerns and Classes We talked about separation of concerns when we were discussing modularization in Chap. 9. Basically this means that some details are put in one module and another module doesn’t have to know anything about those details—just the data needed and the data returned. The same idea applies to classes. You can “hide” implementation details (variables and methods) in class definitions; the main() module doesn’t need to have anything to do with the details of a class. The concerns of a class don’t concern the main module.
17
Or, Encapsulation This is also called encapsulation. What we mean by this is that the implementation details of a class are encapsulated in the class definition—sealed off, insulated, hidden— from the other modules in the program. In the MSdie example, all the details about the die are encapsulated in the MSdie class definition, and the main() module has nothing to do with those details.
18
Any good programmer knows he/she must document code—to clarify what the use of a function is, to explain variables and how they mutate, etc. Python provides a special way of accessing long comments built into source code to explain classes, functions, variables, etc. These are called docstrings, and they are embedded in code using triple double quotation marks.
19
Example of embedded docstring: class BeerCan: “””This class provides a virtual representation of that liquid refreshment of which so many of us partake on weekends.””” To extract this commentary: >>>print BeerCan.__doc__
20
If you import a library, or if you just want documentation and help with standard functions, you can use the command from the last slide, or >>>help(raw_input) Try this in the Python interpreter. Find help documentation for raw_input(), input(), print. Import the string library and get help on split(), rfind(), and find()
21
Graphical elements on a Python graphics window are called widgets. An entry box is a widget; so are objects we draw and labels. You can create classes of widgets that will standardize the appearance of those elements on your window. The textbook includes a class for creating a button which will change appearance when clicked. You could also create a class which makes standardized labels for your online shop.
22
Copy button.py from our class website into your working Python directory. Then write a short code which imports button.py and creates a graphic window where one button will appear. Run your code, and see if the button changes appearance when clicked.
23
Let’s work through the dice code from our textbook: 1) what does button.py do? 2) work through dieview.py; save this file to your working Python directory 3) work through roller.py; save this file to your working Python directory 4) run roller.py
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.