Object-oriented programming

From CS 61A Wiki
Revision as of 13:05, 24 July 2014 by Axis (Talk | contribs)


Jump to: navigation, search

Object-oriented programming (OOP) is a method of programming using objects that store/organize their own data and interact with each other via their methods. Programming languages that support OOP provide a built-in way to implement data abstractions, as classes correspond to abstract data types (ADTs).

Motivation

Terminology

Syntax

Adding methods after defining the class

To add a method to a class after defining the class:

Class.method = lambda self: ret_value

To add a method to an instance of a class:

inst.method = lambda: "test"

Examples:

>>> class A:
...     def __init__(self, x):
...         self.x = x
... 
>>> A.prev = lambda self: self.x - 1
>>> a = A(1)
>>> a.prev()
0
>>> class A:
...     def __init__(self, x):
...         self.x = x
... 
>>> a = A(1)
>>> a.prev = lambda: a.x - 1
>>> a.prev()
0

Inheritance

Main article: Inheritance

Sources