-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgrok_python.py
More file actions
60 lines (48 loc) · 1.34 KB
/
grok_python.py
File metadata and controls
60 lines (48 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
Grokking Python:
https://kirbyurner.medium.com/grokking-python-9f96140c1e07?sk=d1ec6762e753d5c79106faf1669fcb04
(friend link)
Python's Rib Cage:
https://kirbyurner.medium.com/pythons-rib-cage-e4ff16cf3a74?sk=3e59d2356de6a13b42c9cf61d4d6a308
(friend link)
In this more advanced version, we study inheritance
"""
class Animal:
def __init__(self, nm):
"An animal is born..."
self.name = nm
self.stomach = [ ] # born with an empty stomach
def eat(self, food):
"Add a food to my stomach"
self.stomach.append(food)
def __call__(self, food):
self.eat(food)
def __repr__(self):
"Repper -- represent me"
return f"a {type(self).__name__} named {self.name}"
def __add__(self, other):
"Combine names for the new animal of self type"
return type(self)(self.name + other.name)
class Cat(Animal):
"""
the Cat type
"""
def meow(self, n):
return "Meow! " * n
class Dog(Animal):
"""
the Dog type
"""
def bark(self, n):
return "Meow! " * n # bug! FIXME
if __name__ == "__main__":
rover = Dog("Rover")
kitty = Cat("Kitty")
print(rover)
print(kitty)
rover.eat(kitty)
print(rover.stomach)
rover(rover)
print(rover.stomach)
new_animal = rover + kitty
print(new_animal)