def f(x, y):
print("values: ", x, y)
f(42, 43)
f(42, 43.7)
f(42.3, 43)
f(42.0, 43.9)
What is the difference compared to functions in C, C++, Java?
Inheritance did not arise only because programmers were lazy and didn’t want to write the same code twice. If we know that every Kitten and Puppy, or any other subclass, is an animal, we can create a list of animals without caring about the exact type:
zvieratka = [Kitten('Micka'), Puppy('Dunco')]
for zvieratko in zvieratka:
zvieratko.zjedz('pamlsok')
This is a very important property of subclasses: if we have a Kitten, we can use it anywhere the program expects an Animal, because every kitten is an animal.
This is a helpful guideline when you are unsure which class should inherit from which. Every kitten or puppy is an animal, every cottage or apartment building is a building. In such cases, inheritance makes sense.
Sometimes, however, applying this guideline leads to nonsense, for example: “every car is a steering wheel.” In this case, we do not use inheritance. Even though both a steering wheel and a car can be turned to the right, it means something different for each. It makes more sense to say: “every car has a steering wheel,” just like “every kitten has a name.” Therefore, it is more appropriate to create two classes and connect them like this:
class Car:
def __init__(self):
self.steering_wheel = SteeringWheel()
Create two classes, Cat and Dog, each with a method make_sound(). Each class implements this method differently – the cat returns “Meow”, the dog returns “Woof”. Then create a list of animals and call make_sound() on each object in a loop.
Create a parent class Animal with a method make_sound() that returns “Some sound”. Then create subclasses Cat and Dog that override this method with their own implementations (“Meow” and “Woof”). Finally, create a list of objects of different classes and call make_sound() on them.
Create a function add(x, y) that returns the sum of two values. Test it with numbers, strings, and lists. The function should correctly work with all these input types.
Create classes Car and Bike with a method __str__() returning “I am a car” and “I am a bike”. Then create a list of instances of these classes and print them in a loop using print().
Create classes Circle and Square with a method area(). Circle should compute the area using the formula π * r², and Square using a². Then create a list of objects of these classes and print their areas.