magic methods demo

This commit is contained in:
waldek 2022-04-19 23:53:06 +02:00
parent bba8d1c851
commit b4b40f1790
1 changed files with 63 additions and 0 deletions

View File

@ -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.
<!---
# Coding challenge - Bus line
There is a bus line with with 20 stops on it.
@ -2502,6 +2503,68 @@ Throughout the day 4 buses will pass by and each bus has 30 seats on it.
**TODO**
</details>
--->
## 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