Intro to
(with Python)

Fall 2018

Thu Nov 1

defining classes

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)

special methods

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): = one
        self.two = two
        self.three = three
    def __len__(self):
        return 3
    def __repr__(self):
        return "Triple(one={}, two={}, three={})".format(
  , 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 = +,
                      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

class variables vs instance variables

Check out my example which illustrates inheritance, class variables, and container classes. /cours /fall2018 /python /notes /objects
last modified Tue December 5 2023 8:47 am