Difference between revisions of "Class"

From CS 61A Wiki
Jump to: navigation, search
[checked revision][checked revision]
(copyedit; reorganize)
 
(3 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 +
{{Sufficient-class}}
 
{{OOP sidebar}}
 
{{OOP sidebar}}
==Class==
+
A '''class''' is an [[object]] that is a blueprint for its instance objects. It has an <code>__init__</code> method that is called when a new instance is created.
A '''class''' is an object that is a representation of its instance objects, and helps to classify or categorize the information that is stored ot it. It has [[Attribute#@property|getter]] and [[Attribute#@property|setter]] methods that allow you to access and manipulate the data stored in a class instance. Classes also have a ''new'' method that, when called, creates a new instance of the class object with the ''__init__'' method and arguments provided if necessary.  
+
 
 +
==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 <code>__init__</code> function definition will result in a function object bound to name <code>__init__</code> in the class object.
 +
<syntaxhighlight lang="python">
 +
>>> class A:
 +
...    print(1+1)
 +
...    def __init__(self, elem):
 +
...        self.elem = elem
 +
2
 +
>>> A
 +
<class '__main__.A'>
 +
>>> callable(A)
 +
True
 +
</syntaxhighlight>
 +
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:
 +
# First, Python will create a new blank object of class A. Can be controlled with <code>__new__</code>, but this magic method is outside the scope of this course.
 +
# Python will then invoke <code>__init__</code> on this blank object (this blank object gets bound to <code>self</code>), along with the other arguments passed into the class constructor.
 +
# Finally, after <code>__init__</code> has finished executing, Python will return the now-initialized object.
 +
<syntaxhighlight lang="python">
 +
>>> 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
 +
</syntaxhighlight>
  
 
==Implementation==
 
==Implementation==

Latest revision as of 15:08, 24 July 2014

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