New Objects by Subclassing

The built-in objects are, well, built into Python. They're there when we start Python, usually there when we finish. So how can we create new objects?

New objects cannot pop out of thin air. They have to be built using existing objects.

Example 2.4. Creating new objects by subclassing

# In Python 2.x:
class C(object): 1
    pass

# In Python 3.x, the explicit base class is not required, classes are
# automatically subclasses of object:
class C: 2
    pass

class D(object):
    pass

class E(C, D): 3
    pass

class MyList(list): 4
    pass 


1

The class statement tells Python to create a new type by subclassing an existing type.

2

Don't do this in Python 2.x or you will end up with an object that is an old-style class, everything you read here will be useless and all will be lost.

3

Multiple bases are fine too.

4

Most built-in types can be subclassed (but not all).

After the above example, C.__bases__ contains <type 'object'>, and MyList.__bases__ contains <type 'list'>.