Python classes

References

Summary

Class members are public and class member functions are virtual Classes are objects

Types and classes are essentially the same thing, but the keywords type and class do different things

Object-oriented programming is based on encapsulation

Definitions

Methods

Methods are the functions inside of a class

class MyClass:
    def f(self):

x = MyClass
x.f    

The function f created from MyClass is a function object x.f is a method object

xf = x.f

Methods can call other methods in the same class They can also references things in the global scope

Attributes

Attributes are the variables inside of a class

You access both of these with a period

Instantiation

class MyClass:
    ...

x = MyClass()

A priori, the nwew instance of the class MyClass will be empty

Sharing Data

class Dog:

tricks = []             # mistaken use of a class variable

def __init__(self, name):
    self.name = name

def add_trick(self, trick):
    self.tricks.append(trick)

d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')



>>> d.tricks                # unexpectedly shared by all dogs
['roll over', 'play dead']

The problem here is that the tricks list is a class variable, and thus will be shared by all instances of the class

Instead if we move the variable to the instance

class Dog:

def __init__(self, name):
    self.name = name
    self.tricks = [] # creates a new empty list for each dog

def add_trick(self, trick):
    self.tricks.append(trick)

d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')



>>> d.tricks                # unexpectedly shared by all dogs
['roll over', 'play dead']

Derived Classes

class DerivedClassName(BaseClassName):

Given one class, we can create a new derived class from it

Multiple Inheritance

You can actually create a derived class that's built off of multiple base classes

class DerivedClassName(Base1, Base2):

When searched for attributes this will

  1. Check DerivedClassName
  2. Check all of Base1 (including any base classes, if Base1 is itself derived)
  3. Do the same for Base2

It uses the call-next-method

Private Variables

Python has no private variables

The convention is to prefix with an underscore

Name mangling

Iterators

Methods List

__init__

This puts a newly created instance of the class into a specific initial state

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart

x = Complex(1,1)          

__iter__

This method returns a new iterator object that has the method __next__

There is also a built-in iter function, which is called by any for loop

If you add the iter method to a class

__next__

Returns the next item from an iterator object

If there are no more items, it raises the StopIteration exception

class MyClass:
    def __init__(self,data):
        self.data = data
        self.index = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.index == len(data):
            raise StopIteration
        self.index - self.index + 1
        return self.data[self.index - 1]             

__dict__

Stores an object's writable attributes

def funct():
class C:

print(funct.__dict__)
print(C.__dict__)  

dict allows you to add new attributes to an object

__slots__

Very similar to dict, but it's a static type, rather than dynamic

class C:
  __slots__ = ...

__add__

a + b   is interpretted as a.__add__(b)

__radd__

If we try

int.__add(1, x)

for an object x, we'll get a NotImplemented error

So if we define an addition method on type(x), we can then define

def __radd__(self, other):
  return self + other

(assuming addition is commutative)

__call__

This is used to make an object behave like a function

__eq__

Used to define when two objects of the same class are equal

__enter__

Used in context managers When it's called, you enter the runtime context of the object

__exit__

Exits the runtime context of the object

Conventions

Classes are named in PascalCase

Non-public starts with a leading underscore

Name mangling

Metaclasses