CS61A Lecture 15: Objects

3 Pages
Unlock Document

Computer Science
De Nero

Object-Oriented Programming A method for organizing programs Data abstraction Bundling together information and related behavior A metaphor for computation using distributed state Each object has its own local state Each object also knows how to manage its own local state, based on method calls Method calls are messages passed between objects Several objects may all be instances of a common type Different types may relate to each other Specialized syntax & vocabulary to support this metaphor Classes (type of object) A class serves as a template for its instances Idea: All bank accounts have a balance and account holder; the Account class should add attributes to each newly created instance Ex: a = Account('Jim') a.holder = 'Jim' a.balance = 0 Idea: All bank accounts should have "withdraw" and "Deposit" behaviors that all work in the same way Better Idea: All bank accounts share "withdraw" and a "deposit" method Class statement class : A class statement creates a new class and binds that class to in first frame of current environment Statements in the create attributes of the class (suite executed right away) As soon as instance is created, it is passed to __init__, which is attribute of class called constructor method. class Account: def __init__(self, account_holder): self.balance = 0 self.holder = account_holder Initialization Idea: All bank accounts have balance and an account holder; the Account class should add those attributes to each of its instances Almost always use __init__ after class When class called: 1. A new instance of that class is created 2. Constructor __init__ of the class is called with new object as its first argument (named self), along with any additional arguments provided in the call expression Object Identity Every object that is instance of user-defined class has unique identity Every call to Account creates new Account instance. Only one account class. Identity testing is performed by "is" and "is not" operators Binding an object to new name using assignment does not create new object Methods Methods are defined in the suite of a class statement def deposit(self, amount): """Add amount to balance.""" self.balance = self.balance + amount return
More Less

Related notes for COMPSCI 61A

Log In


Join OneClass

Access over 10 million pages of study
documents for 1.3 million courses.

Sign up

Join to view


By registering, I agree to the Terms and Privacy Policies
Already have an account?
Just a few more details

So we can recommend you notes for your school.

Reset Password

Please enter below the email address you registered with and we will send you a link to reset your password.

Add your courses

Get notes from the top students in your class.