Exercises
Methods
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Add learn and show methods so the dog can collect tricks.
Python
class Dog:
def __init__(self, name):
self.name = name
self.tricks = []
rex = Dog("Rex")
rex.learn("sit")
rex.learn("roll")
print(rex.show())Both methods take self first, and reach the data through it.
class Dog:
def __init__(self, name):
self.name = name
self.tricks = []
def learn(self, trick):
self.tricks.append(trick)
def show(self):
return f"{self.name} knows: {', '.join(self.tricks)}"
rex = Dog("Rex")
rex.learn("sit")
rex.learn("roll")
print(rex.show())Exercise 2Passed
Make area a property so it recalculates when width changes.
Python
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
self.area = width * height
r = Rectangle(3, 4)
print(r.area)
r.width = 10
print(r.area)Decorate a method with @property and drop the stored value.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
r = Rectangle(3, 4)
print(r.area)
r.width = 10
print(r.area)Exercise 3Passed
Add a classmethod called puppy that builds a Dog aged 0.
Python
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
rex = Dog.puppy("Rex")
print(rex.name, rex.age)@classmethod, and the first parameter cls is the class itself.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def puppy(cls, name):
return cls(name, 0)
rex = Dog.puppy("Rex")
print(rex.name, rex.age)