Chapter 10 gives lots of examples, which I've put into this folder.
Code to look at :
topics to discuss and study ... some outside of textbook material :
(Coming ... maybe Thursday)
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.