Difference between revisions of "Class"

From CS 61A Wiki
Jump to: navigation, search
[checked revision][checked revision]
m ({{C-class}})
Line 1: Line 1:
 +
{{C-class}}
 
{{OOP sidebar}}
 
{{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. 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.  
 
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.  
  

Revision as of 10:20, 21 July 2014

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