CS61A(16): Objects

This is the lecture note of CS61A - Lecture 16.

OOP (Object-Oriented Programming)

Objects are organized according to classes.

  • A class combines (and abstracts) the storing of information data and functionality on the data (data + methods).
  • An object is an instantiation of a class.

Class Statements

Class statements let you create any type of data you want.

1
2
3
4
5
6
>>> a = Account('Jim')
>>> b = Account('Jack')
>>> a is b
False
>>> a is not b
True

Constructors,

  • allocate memory for an object
  • initialize an object with values
  • return address of the object

Methods

Objects receive messages via dot notation. Dot notation accesses attributes of the instance or its class.

1
2
3
4
5
6
<expression>.<attribute_name>

"""
expression can be any valid Python expression
attribute can be data or methods;
"""

Attributes

Class attributes are "shared" across all instances of a class because they are attributes of the class, not the instance.

Code

Code of today's lecture:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Account:
"""An account has a balance and a holder.
All accounts share a common interest rate.

>>> a = Account('John')
>>> a.holder
'John'
>>> a.deposit(100)
100
>>> a.withdraw(90)
10
>>> a.withdraw(90)
'Insufficient funds'
>>> a.balance
10
>>> a.interest
0.02
>>> Account.interest = 0.04
>>> a.interest
0.04
"""

interest = 0.02 # A class attribute

def __init__(self, account_holder):
self.holder = account_holder
self.balance = 0

def deposit(self, amount):
"""Add amount to balance."""
self.balance = self.balance + amount
return self.balance

def withdraw(self, amount):
"""Subtract amount from balance if funds are available."""
if amount > self.balance:
return 'Insufficient funds'
self.balance = self.balance - amount
return self.balance