Exercises
Classes and Objects
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Define a Dog class with a shared species attribute, build one, and print the species.
Python
# define Dog with species, then build one and print it
A value assigned in the class body is shared by every object.
class Dog:
species = "canis familiaris"
rex = Dog()
print(rex.species)Exercise 2Passed
Both dogs share one tricks list. Show it: append through one and print the other's.
Python
class Dog:
tricks = []
rex = Dog()
fido = Dog()
# append through rex, then print fido's
There is one list, on the class, not one per object.
class Dog:
tricks = []
rex = Dog()
fido = Dog()
rex.tricks.append("sit")
print(fido.tricks)Exercise 3Passed
Objects are mutable, so a function can change one. Make bump add one to the counter.
Python
class Counter:
pass
def bump(c):
# add one to c.value
pass
counter = Counter()
counter.value = 0
bump(counter)
bump(counter)
print(counter.value)The parameter is another name for the same object.
class Counter:
pass
def bump(c):
c.value += 1
counter = Counter()
counter.value = 0
bump(counter)
bump(counter)
print(counter.value)