Exercises
self
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
The method is missing self, so calling it fails. Fix it.
Python
class Dog:
def speak():
return "woof"
print(Dog().speak())Python passes the object as the first argument whether you name it or not.
class Dog:
def speak(self):
return "woof"
print(Dog().speak())Exercise 2Passed
This sets a local that is thrown away. Make it set the object's value instead.
Python
class Counter:
def __init__(self):
self.value = 0
def set_to_99(self):
value = 99
c = Counter()
c.set_to_99()
print(c.value)Attributes need self in front.
class Counter:
def __init__(self):
self.value = 0
def set_to_99(self):
self.value = 99
c = Counter()
c.set_to_99()
print(c.value)Exercise 3Passed
Add older_than so one dog can be compared with another.
Python
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
print(Dog("Rex", 5).older_than(Dog("Fido", 3)))self is an ordinary object, and so is the one passed in.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def older_than(self, other):
return self.age > other.age
print(Dog("Rex", 5).older_than(Dog("Fido", 3)))