Modules
->
OOP
->
Methods
->
Adding objects
Adding objects
Related code
class Dog: """Represents a dog. attributes: name: str, age: int, energy: int """ def print(self): print(f'Name: {self.name}, Age: {self.age}') def set_info(self, name, age, energy): self.name = name self.age = age self.energy = energy def play(self, hours): self.energy -= hours * 10 def sleep(self, hours): self.energy += hours * 10 def is_older(self, other): return self.age > other.age murki = Dog() murki.set_info("Murki", 2, 50) reksi = Dog() reksi.set_info("Reksi", 1, 50)
When we compared two dogs, it was easier to find the way how to compare them. We named the method
is_older
and logically we had to compare their ages.
Now we want to add two dogs, and adding two dogs is not logical in daily life, but for some reason we need such functionality. For example:
- We may want to create a dog which is as old as two dogs.
- We may want to create a dog which has as much energy as two dogs.
- Or we may want to create a dog which is as old and has as much energy as two dogs.
Let's go with the last one:
class Dog: ... def add(self, other): new_dog = Dog() new_dog.set_info(self.name + other.name, self.age + other.age, self.energy + other.energy) return new_dog ...
add
takes two dogs, self
and other
,
and returns a new dog that is as old as has as much energy as both of them, and the new dog's name is
a combination of their names.
>>> sharki = murki.add(reksi, 'Sharki') >>> sharki.print() Name: MurkiReksi, Age: 3 >>> sharki.energy 100