Transcript Slide 1

Advanced Classes
Wrestling with Python
Classes
©Rob Miles
What we can do so far...
•
•
•
•
•
•
•
Store data (using variables)
Change data (using expressions)
Make decisions (using conditions)
Create loops (using while and for)
Write methods (using def)
Store data in lists (using er, lists)
Create and use class types
Classes In Python
21-Jul-15
©Rob Miles
2
Classes
• We can now create our own types of
variable
• We can decide what happens inside the
variable (methods) and what is stored
there (attributes)
• We can add attributes dynamically
Classes In Python
21-Jul-15
©Rob Miles
3
Classes
• We can now create our own types of
variable
• We can decide what happens inside the
variable (methods) and what is stored
there (attributes)
• We can add attributes dynamically
BUT THIS IS A BAD THING TO DO
Classes In Python
21-Jul-15
©Rob Miles
4
Constructing Objects Properly
Classes In Python
21-Jul-15
©Rob Miles
5
House Rules
• A program should set up the attributes for
your objects when an instance is created
• That way you can be sure that all the
objects are completely interchangeable
• You do this in the constructor for an object
Classes In Python
21-Jul-15
©Rob Miles
6
A player constructor
class player:
def __init__(self, name, score):
self.name = name
self.score = score
• The constructor method (__init__) is
called when a new player is created
• It puts the name and the score values into
the object attributes
Classes In Python
21-Jul-15
©Rob Miles
7
Creating an object
p = player('Fred', 10)
print(p.name)
• We saw that this will create a object and
set the name and the score to the values
• The program above will print out ‘Fred’
Classes In Python
21-Jul-15
©Rob Miles
8
Bad Creation
p = player(10, 'Fred')
print(p.name)
• This will create a player with the name 10
and the score ‘Fred’
• Bad things will happen when we use this
object
– The score is now a string
Classes In Python
21-Jul-15
©Rob Miles
9
Clearer Calling
p = player(score=0, name='Fred')
• One way to solve this problem is to
actually identify the attributes that are
being set
• You should strongly encourage this
• It reduces the chances of mistakes
Classes In Python
21-Jul-15
©Rob Miles
10
Sensible Constructor
class player:
def __init__(self, name, score):
if type(name) is str:
self.name = name
else:
raise Exception("Invalid player name type")
if type(score) is int:
self.score = score
else:
raise Exception("Invalid player score type")
• This constructor stops the program if it is
given bad data
Classes In Python
21-Jul-15
©Rob Miles
11
Sensible Constructor
class player:
def __init__(self, name, score):
if type(name) is str:
self.name = name
else:
raise Exception("Invalid player name type")
if type(score) is int:
self.score = score
else:
raise Exception("Invalid player score type")
• The type method will extract the type data
from a variable
Classes In Python
21-Jul-15
©Rob Miles
12
Sensible Constructor
class player:
def __init__(self, name, score):
if type(name) is str:
self.name = name
else:
raise Exception("Invalid player name type")
if type(score) is int:
self.score = score
else:
raise Exception("Invalid player score type")
• You can test to check if the type the one
that is required
Classes In Python
21-Jul-15
©Rob Miles
13
Sensible Constructor
class player:
def __init__(self, name, score):
if type(name) is str:
self.name = name
else:
raise Exception("Invalid player name type")
if type(score) is int:
self.score = score
else:
raise Exception("Invalid player score type")
• If the type is correct we set the attribute
Classes In Python
21-Jul-15
©Rob Miles
14
Sensible Constructor
class player:
def __init__(self, name, score):
if type(name) is str:
self.name = name
else:
raise Exception("Invalid player name type")
if type(score) is int:
self.score = score
else:
raise Exception("Invalid player score type")
• If the type is wrong we raise an exception
and stop the program
Classes In Python
21-Jul-15
©Rob Miles
15
Raising an exception
Traceback (most recent call last):
File "C:\Users\Rob\SkyDrive\Wrestling with
Python\Season 2\Week 05 Advanced
Classes\cricket_class.py", line 16, in <module>
p = player(score=0, name=0)
File "C:\Users\Rob\SkyDrive\Wrestling with
Python\Season 2\Week 05 Advanced
Classes\cricket_class.py", line 6, in __init__
raise Exception("Invalid player name type")
Exception: Invalid player name type
• If we raise an exception we stop the
program and display an error
Classes In Python
21-Jul-15
©Rob Miles
16
Creating a safe constructor
PRACTICAL BREAK 1
Classes In Python
©Rob Miles
21-Jul-1517
Static Class Variables
Classes In Python
21-Jul-15
©Rob Miles
18
Static Class Variables
• We have seen how a program can add
attributes to instances of a class
• We can also add “static” variables to a
class as well
• A static variable is part of the class
• It is created once when the class is loaded
Classes In Python
21-Jul-15
©Rob Miles
19
Using a static variable
class player:
count = 0
def __init__(self, name, score):
self.name = name
self.score = score
player.count = player.count + 1
• The variable count is static
• We use it to count how many players we
have created
Classes In Python
21-Jul-15
©Rob Miles
20
Using a static variable
class player:
count = 0
def __init__(self, name, score):
self.name = name
self.score = score
player.count = player.count + 1
• If you think about, if count was stored for
each instance of player the counting would
not work
Classes In Python
21-Jul-15
©Rob Miles
21
Using a static variable
class player:
count = 0
def __init__(self, name, score):
self.name = name
self.score = score
player.count = player.count + 1
• The program does not use self to access a
static variable, instead the name of the
class is used
Classes In Python
21-Jul-15
©Rob Miles
22
Uses for static variables
• There are quite a few uses for class wide
values
– Maximum or minimum values for attributes
• Largest and smallest number of runs allowed
– Settings that are held for the entire class
• Tax or interest rates
– Default values for settings
• Values to insert if they are not given in the call of
the constructor
Classes In Python
21-Jul-15
©Rob Miles
23
Counting players
PRACTICAL BREAK 2
Classes In Python
©Rob Miles
21-Jul-1524
Class Design
Classes In Python
21-Jul-15
©Rob Miles
25
Class Design
• We can build data structures by creating
classes that contain other classes
• We can also create classes that define a
relationship between two other classes
– Receipt: contains a reference to a customer
and also the videogame that they have just
bought
Classes In Python
21-Jul-15
©Rob Miles
26
Creating an address class
class address:
def __init__(self, firstLine, postcode):
self.firstLine = firstLine
self.postcode = postcode
• This is a simple class that holds an address
as a first line and a postcode
• You can add other items here if you like
Classes In Python
21-Jul-15
©Rob Miles
27
Creating an address class
class player:
def __init__(self, name, score, playerAddress):
self.name = name
self.score = score
self.playerAddress = playerAddress
• This version of player also holds an
address value
• This is passed in when the instance of the
player is created
Classes In Python
21-Jul-15
©Rob Miles
28
Adding an address to a player
pAddress = address('Hull', 'HU6 7RX')
p = player('Fred', 10, pAddress)
print(p.playerAddress.firstLine)
• This code creates a new address value and
then creates a player with that address
• Finally it prints the first line of the address
of the player that was created
Classes In Python
21-Jul-15
©Rob Miles
29
Adding new data item
PRACTICAL BREAK 3
Classes In Python
©Rob Miles
21-Jul-1530
Classes and Jelly
Classes In Python
21-Jul-15
©Rob Miles
31
“Jelly” classes
• Note that at no point do we explicitly say
that the playerAddress attribute must hold
an address value
– Although we could check the type in the
constructor and reject the wrong ones
• This is the way Python works, the types of
the connections are “made” made up as
the program runs
Classes In Python
21-Jul-15
©Rob Miles
32
Finding out what is in a variable
pAddress = address('Hull', 'HU6 7RX')
print (pAddress.__dict__)
• The __dict__ attribute of an instance
produces a report of what is in an object:
{'postcode': 'HU6 7RX', 'firstLine': 'Hull'}
• The report gives the names of the
attributes and their values
Classes In Python
21-Jul-15
©Rob Miles
33
Jelly Programs
• The great thing about the way Python lets
you add attributes is that it makes it very
easy to design your data storage as your
program runs
• However you need to make sure that this
doesn’t cause confusion when the program
runs
Classes In Python
21-Jul-15
©Rob Miles
34
Summary
• You can add validation to a class
constructor to make sure that the correct
type of data is passed in when an object is
created
• The constructor can raise an exception if
the wrong things are supplied
• Classes can contain static values that are
always present
Classes In Python
21-Jul-15
©Rob Miles
35
Storing a number of player objects
PRACTICAL BREAK 2
Classes In Python
©Rob Miles
21-Jul-1536