From b4b40f17901377a34a8e53b7b24ba8a57c10470d Mon Sep 17 00:00:00 2001 From: waldek Date: Tue, 19 Apr 2022 23:53:06 +0200 Subject: [PATCH] magic methods demo --- learning_python3.md | 63 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/learning_python3.md b/learning_python3.md index 39b70be..65b8367 100644 --- a/learning_python3.md +++ b/learning_python3.md @@ -2462,6 +2462,7 @@ for dog in all_my_dogs: Think of some other world objects you can create a class for and do so. The first one that comes to mind is vehicles but you can do anything that makes sense to you. + + +## Magic methods + +```python +import random + + +SEXES = ["male", "female"] + + +class Dog(object): + SOUND = "woof" + + def __init__(self, name, age, sex): + self.name = name + self.age = age + self.sex = sex + + def __str__(self): + if self.age > 3: + bark = self.__class__.SOUND.upper() + else: + bark = self.__class__.SOUND.lower() + return "{} barks {}".format(self.name, bark) + + def __add__(self, other): + if self.sex == other.sex: + return None + name_part_1 = self.name[0:int(len(self.name) / 2)] + name_part_2 = other.name[0:int(len(self.name) / 2)] + name = name_part_1 + name_part_2 + child = Dog(name, 0, random.choice(SEXES)) + return child + + +if __name__ == "__main__": + dog_1 = Dog("bobby", 4, SEXES[0]) + dog_2 = Dog("molly", 4, SEXES[1]) + dog_3= Dog("rex", 4, SEXES[0]) + puppy = dog_1 + dog_2 + dog_3 + print(puppy) + +``` + +```python +class DataBase(object): + def __init__(self, data): + self.data = data + + def __iter__(self): + for element in self.data: + yield element + + +if __name__ == "__main__": + db = DataBase(['hello', "world", "test", "one", "two"]) + for item in db: + print(item) +``` + +* [more information](https://rszalski.github.io/magicmethods/) ## Class inheritance