Difference between revisions of "Class"

From CS 61A Wiki
Jump to: navigation, search
[unchecked revision][checked revision]
(Created page with "{{OOP sidebar}} ==Class== 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...")
 
Line 4: Line 4:
  
 
==Implementation==
 
==Implementation==
Implementing a class requires a ''getter'', ''setter'', and a ''new'' method< ref>http://composingprograms.com/pages/26-implementing-classes-and-objects.html#classes</ref>.  
+
Implementing a class requires a ''getter'', ''setter'', and a ''new'' method  
 +
<ref>http://composingprograms.com/pages/26-implementing-classes-and-objects.html#classes</ref>.  
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">

Revision as of 17:53, 18 July 2014

Class

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 getter and 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.

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