Difference between revisions of "Object-oriented programming"

From CS 61A Wiki
Jump to: navigation, search
[checked revision][checked revision]
(add example; copyedit)
m (fix)
Line 19: Line 19:
 
* [[Attribute|attribute access/assignment]]
 
* [[Attribute|attribute access/assignment]]
  
== Adding methods after defining the class ==
+
=== Adding methods after defining the class ===
 
To add a method to a class after defining the class:
 
To add a method to a class after defining the class:
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
Line 42: Line 42:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 +
<syntaxhighlight lang="python">
 
>>> class A:
 
>>> class A:
 
...    def __init__(self, x):
 
...    def __init__(self, x):
 
...        self.x = x
 
...        self.x = x
...    def next(self):
 
...        return self.x + 1
 
 
...  
 
...  
 
>>> a = A(1)
 
>>> a = A(1)
Line 52: Line 51:
 
>>> a.prev()
 
>>> a.prev()
 
0
 
0
 +
</syntaxhighlight>
  
 
== Inheritance ==
 
== Inheritance ==

Revision as of 13:05, 24 July 2014

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