Class

From CS 61A Wiki
Jump to: navigation, search

A class is an object that is a blueprint for its instance objects. It has an __init__ method that is called when a new instance is created.

Defining

Defining a class results in a class object, just as defining a function creates a function object. Note than unlike functions, all the code inside the class definition is run as if the class object were a frame.

Example: the __init__ function definition will result in a function object bound to name __init__ in the class object.

>>> class A:
...     print(1+1)
...     def __init__(self, elem):
...         self.elem = elem
2
>>> A
<class '__main__.A'>
>>> callable(A)
True

Note that the class itself is callable. Now to construct actual instances of class A (equivalently of "type" A), one has to call the class. The class object now acts as a constructor. Python will follow 3 steps:

  1. First, Python will create a new blank object of class A. Can be controlled with __new__, but this magic method is outside the scope of this course.
  2. Python will then invoke __init__ on this blank object (this blank object gets bound to self), along with the other arguments passed into the class constructor.
  3. Finally, after __init__ has finished executing, Python will return the now-initialized object.
>>> a = A(5)
>>> a
<__main__.A object at 0x...>
>>> type(a) is A
True
>>> b = a
>>> b is a
True
>>> A(5) is a
False

Implementation

Implementing a class requires a getter, setter, and a new method [1].

>>> # From Section 2.6.2 of Composing Programs by John DeNero (see citation)
>>> def make_class(attributes, base_class=None):
        """Return a new class, which is a dispatch dictionary."""
        def get_value(name):
            if name in attributes:
                return attributes[name]
            elif base_class is not None:
                return base_class['get'](name)
        def set_value(name, value):
            attributes[name] = value
        def new(*args):
            return init_instance(cls, *args)
        cls = {'get': get_value, 'set': set_value, 'new': new}
        return cls

Here, the new function calls the init_instance function which creates a new instance of the class using the __init__ method.

>>> def init_instance(cls, *args):
        """Return a new object with type cls, initialized with args."""
        instance = make_instance(cls)
        init = cls['get']('__init__')
        if init:
            init(instance, *args)
        return instance


References

  1. http://composingprograms.com/pages/26-implementing-classes-and-objects.html#classes