ECS 36A Lecture Notes - Lecture 7: Iter, Chromosome, Init
63 views2 pages
6 Nov 2018
School
Department
Course
Professor

ECS 36A - Lecture 7 - Classes
if word in d:
d[word] += 1
else:
d[word] = 1
~this requires checking the dictionary two times per iteration~
try:
d[word] += 1
except keyError:
d[word] 1
~this is more efficient because for more common cases you only have to check the
dictionary once ~
Classes are much more powerful than functions:
● Allows you to create objects and associate multiple functions and attributes to each
object within a class
● Classes help to simplify programs and make them appear more organized
● Useful when multiple a program needs multiple functions need access to be able to
change and alter the same variables
○ Will be useful in HW 3 & 4 of this course
class Human:
chromosome = 23
def __init__(self, name, gender):
self.name = name
self.gender = gender
def get_name(self):
return self.name
print(Human.chromosome) prints 23
# print(Human.name) # Error name is not an attribute
alice = Human('Alice', False)
bob = Human('Bob', True)
print(alice.chromosome, alice.name, alice.gender)
print(bob.chromosome, bob.name, bob.gender)
print(alice.get_name())
print(Human.get_name(alice))