Midterm projects are due today!
I'll take a look and organize things a bit, and then on Thursday I'd like you to do a brief show-n-tell of what you've done.
Any questions about anything?
Today we're starting look at how to define your own object, which python are called "classes".
Chapter 10 gives lots of examples, which I've put into this folder.
Code to look at :
Try this one in the pythontutor :
import random
class Dice:
def __init__(self, sides=6):
self.sides = sides
self.value = 1
def roll(self):
self.value = random.randint(1, self.sides)
def main():
fourD6 = []
for i in range(4):
d6 = Dice()
d6.roll()
fourD6.append(d6)
print("You roll four six-side dice and get ", end='')
for die in fourD6:
print(", {}".format(die.value), end='')
print('')
main()
topics to discuss and study ... some outside of textbook material :
See python3 docs datamodel special-method-names
The notion is that you can create your own objects which have behaviors like Python's built-in data types, by defining methods with particular names. This means that a class that you define can behave like a number, or a string, or a list, or even a function. You can define for example a MyList class and then use python's this_list[i] notation with it. Or you can define your own MyFunction class, create one, and invoke it with this_function(x,y,z). Or your own numbers (like complex numbers) with their own notion of what == or + does.
In some languages this is called "overriding" a behavior or operator.
Here's an example ... without any docs or sample usage. Can you put in what the docs should be? Are there any things that this new object can't do ... but perhaps should?
class Triple:
def __init__(self, one=0, two=0, three=0):
self.one = one
self.two = two
self.three = three
def __len__(self):
return 3
def __repr__(self):
return "Triple(one={}, two={}, three={})".format(
self.one, self.two, self.three)
def __eq__(self, other):
return str(self) == str(other)
def __ne__(self, other):
return not (self == other)
def __add__(self, other):
return Triple(one = self.one + other.one,
two = self.two + other.two,
three = self.three + other.three)
Another object oriented idea that I'd like to at least mention is "inheritance".
See for example prgramiz.com/python-programming.inheritance
Check out my barnyard.py example which illustrates inheritance, class variables, and container classes.
self
, classes, and instancesWhat's going on here?
$ python
>>> class Dog:
... def speak(self):
... return "woof"
...
>>> spot = Dog()
>>> spot.speak()
'woof'
>>>
>>> Dog.speak(spot)
'woof'
Try looking at the interactive prompt for the differences between Dog.speak and spot.speak .
And for a really good time, try
$ python
>>> Dog.noise = 'woof'
>>> Dog.color = 'black'
>>> spot.color = 'brown'
... and then look at spot.noise, spot.color, Dog.noise, Dog.color, and their id() values.
If Dog.noise and Dog.color are now changed, does spot.color or spot.noise change?
Hmmm.