Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
This class has two mistakes. Find them, say what error Python gives, and fix them.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Check self in two places: the parameters of each method, and the attributes.
__init__, name = name makes a local variable and not an attribute. It must be self.name = name. Without the fix, the object has no name.speak, the parameter self is missing. Python passes the object as the first argument, so tom.speak() gives TypeError: Cat.speak() takes 0 positional arguments but 1 was given. (This error comes first, so you see it first.)The fixed class.
Check. It shows Tom says Meow.
Answer: Write self.name = name, and write def speak(self):.
Log in to join the discussion.
Loading…