Python classes

From wikinotes


Anatomy of a Class

A class is an object, that bundles together a set of related variables/functions.

Types of variables:

  • attribute: a variable attached to a class instance
  • class attribute: a variable whose value is shared by all instances of that class

Types of functions:

  • method: a function attached to a class
  • staticmethod: a function attached to a class, that can be called without first instantiating it.
  • classmethod: a function attached to a class, can be called without instantiation, has access to class attributes

If you were writing a class for a car, you might have an attribute speed. You would control that attribute using the methods accelerate() and break().

Python Class Example

class MyClass(object):                        # class <name>( <class inherits from> )
    class_attr = 1

    def __init__(self, *args, **kwargs):      # class-creation arguments. every method 
                                              # receives the keyword 'self' which refers to itself
        self.instance_attr = 0

    def method(self):

    def staticmethod(self):


When a class inherits from a parent class, it receives all of it's methods and attributes. This is referred to as composition. You class can override these methods/attributes.

class MyBaseClass(object):
    def printhi(self):

class MySubClass(MyBaseClass):

In the above example, MySubClass is actually:

class MySubClass(MyBaseClass):
    def printhi(self):

Multiple Inheritance

An object can inherit from multiple parents (although doing this too much can get very hairy). Inheritance is performed as a DAG. All items inheritance is calculated left-to-right.

Dynamic Classes

# ======
# Simple
# ======

## ClassName                 Inherits     Attributes  ##
MyClass = type("MyClass",   (object,),      {}       )

# ===============
# With Attributes
# ===============
MyClass = type("MyClass",   (object,),      { 'x':1, 'y',:2 })

# ============
# With Methods
# ============
def testFunc_MyClass(self, myArg):
	print myArg

MyClass = type("MyClass",   (object,),      { 'testFunc':testFunc_MyClass } )