
|
Lesson 16 Notes: Classes and Methods
- So, what's a class?
- Remember functions?
- Functions are collections of commands that can be used over and over again.
- Classes are similar
- Classes are collections of data and functions that can be used over and over.
- How to Create a Class:
class MyClass:
def hello(self):
print "Welcome."
def math(self, v1, v2):
print v1+v2
- Start with keyword "class"
- Class names are capitalized by convention
- End line with colon, then create body of class
- In body, create function definitions.
- Each function must take "self" as a parameter.
- Using a Class
class MyClass:
def hello(self):
print "Welcome."
def math(self, v1, v2):
print v1+v2
fred = MyClass()
fred.hello()
fred.math(2,4)
- Create an instance of a class by assigning a variable name to it.
- To apply a function to the new instance, you must use a fully qualified name --instance.method()
- If the method takes an argument, be sure to include all needed values.
- A Gradebook Sample Class
class Gradebook:
def __init__(self, name, value):
self.name = name
self.grade = value
self.scores = 1
def addgrade(self, points):
self.scores += 1
self.grade += points
self.average = int(float(self.grade)/self.scores)
print self.name, ": average =", self.average
- Variables inside a class must be accessed by prefixing the variable name with "self."
- The __init__ function is is run whenever a new instance of the class is created.
- Using The Gradebook Class
eli = Gradebook('Eli', 85)
benji = Gradebook('Benji', 90)
beryl = Gradebook('Beryl', 61)
eli.addgrade(92)
benji.addgrade(91)
beryl.addgrade(13)
eli.addgrade(88)
benji.addgrade(89)
beryl.addgrade(92)
- Each new instance of the Gradebook class must have name and first score, because that is what our __init__ function requires.
- Each new instance of the Gradebook class must have name and first score, because that is what our __init__ function requires.
- Each instance will have its own separate average.
- Review
- What is a class?
- What is an instance?
- How do you create and instance of a class?
- How do you use a method within a class?
- What is the __init__ function?
Restricted access |