Objects
Review - Mutability
- What would be the final values of the names defined within this code segment?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def func1(lst1):
lst1 = lst1[0:-1]
return lambda lst: lst + lst1
def func2(lst1):
lst1[0] = lst1.pop()
lst1 = [1, 19, 2022]
lst2 = [5, 10, 2022]
res1 = func1(lst1)
res2 = res1(lst2)
res3 = func2(lst2)
# lst1 = [1, 19, 2022]
# lst2 = [2022, 10]
# res1 = lambda
# res2 = [5, 10, 2022, 1, 19]
# res3 = None
1
[2022, 10]
- Arithmetic operators do not mutate the list, but rather returns a new list. If we wanted to mutate the original list to add new elements, use extend.
Class Statements
- A class describes the behavior of its instances
- Ex: All bank accounts have a balance and an account holder; the Account class should add those attributes to each newly created instance.
- The class is a blueprint for creating objects/instances of that class.
- Every class has attributes and methods.
- Attributes are like variables, they store information.
- Methods are like functions, they perform operations to the Object.
- We access attributes and metjods using the dot notation.
The Account Class
- The keyword “self” refers to the instance of the class itself.
- The
__init__
method is a special method name for the function that constructs an Account instance. - The Class can be thought of as a new type of an object.
- Everything in python belongs to a class
- Methods that include the self arguemnt are instance methods, without self, they are NOT instance methods and do not affect the contents of each instance.
- Other than instance attributes, we may also have class variables that can be accessed freely.
- With self: instance
- Without self: class
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
class Account:
company = "CS61A Bank" # This is a class variable
def __init__(self, account_holder):
self.balance = 0 # This is an instance variable
self.holder = account_holder
def deposit(self, ammount): # This is an instance method
self.balance = self.balance + ammount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
return "Insufficient funds"
self.balance = self.balance - amount
return self.balance
def foo(x): # This is a class method
return Account.company
def transfer(self, into, amount):
result = self.withdraw(amount)
if type(result) == str:
return result
else:
into.deposit(amount)
return "Transfer Successful"
a = Account("Alex")
a.deposit(50000)
b = Account("Bobby")
b.deposit(10000)
a.transfer(b, 20000)
print(a.balance) # 30000
print(b.balance) # 30000
1
2
30000
30000