Professional Documents
Culture Documents
15 Objects
15 Objects
15 Objects
Announcements
2
Object-Oriented Programming
• Data abstraction
Jordan’s
• Bundling together information and related behavior Account Apply for
a loan!
3
Classes
>>> a.deposit(15)
Idea: All bank accounts should have 15
withdraw and deposit behaviors that all work >>> a.withdraw(10)
in the same way 5
>>> a.balance
5
Better idea: All bank accounts share a >>> a.withdraw(10)
withdraw method and a deposit method 'Insufficient funds'
4
Class vs. Object
class object
5
Class Statements
The Class Statement
class <name>:
<suite>
A class statement creates a new class and binds that class to <name> in the first frame of
the current environment
7
`
>>> a = Account('Noor')
>>> a.holder
‘Noor'
>>> a.balance
0
2.The __init__ method of the class is called with the new object as its first
argument (named self), along with any additional arguments provided in the
call expression
class Account:
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder
8
Object Identity
>>> a = Account('Tim')
>>> b = Account(‘Jordan')
>>> a.balance Every call to Account creates a new Account
0 instance. There is only one Account class.
>>> b.holder
‘Jordan'
Identity operators "is" and "is not" test if two expressions evaluate to the same object:
>>> a is a
True
>>> a is not b
True
Binding an object to a new name using assignment does not create a new object:
>>> c = a
>>> c is a
True
9
Methods
Methods
class Account:
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder
self should always be bound to an instance of the Account class
11
Invoking Methods
All invoked methods have access to the object via the self parameter, and so they can all
access and manipulate the object's state
12
Dot Expressions
<expression> . <name>
tom_account.deposit(10)
Call expression
Dot expression
13
Attributes
Accessing Attributes
15
Methods and Functions
>>> type(Account.deposit)
<class 'function'>
>>> type(tom_account.deposit)
<class 'method'>
16
Looking Up Attributes by Name
<expression> . <name>
1. Evaluate the <expression> to the left of the dot, which yields the object of
the dot expression
3. If not, <name> is looked up in the class, which yields a class attribute value
17
Class Attributes
Class attributes are "shared" across all instances of a class because they are attributes
of the class, not the instance
18
Break
Bouncing Balls
20
Ball Instance
22
Ball Class
x: 10.0
b1 = Ball(10.0, 15.0, 0.0, -5.0) y: 15.0
vx: 0.0
vy: -5.0
color: ‘blue’
x: -5.0
y: 1.0
b2 = Ball(-5.0, 1.0, 5.0, -10.0, ‘green’) vx: 5.0
vy: -10.0
color: ‘green’
x: -4.0
y: 1.0
vx: 5.0
b3 = Ball(-4.0, 1.0, 5.0, 10.0 ‘red’)
vy: 10.0
color: ‘red’
[bouncingballs.ipynb]
23
Multi-class programs
[crowd.ipynb]
24