Skip to content

Commit 547d5fb

Browse files
committed
add class inheritance
1 parent 1cb6569 commit 547d5fb

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

cheatsheet.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,3 +215,16 @@ def __str__(self):
215215
print(cat0.speak())
216216
print(cat1.speak())
217217

218+
219+
class MagicalCat(Cat):
220+
catWord = "abracadabra"
221+
222+
def __init__(self, name):
223+
super().__init__(name)
224+
def speak(self):
225+
return f"{self.name} says ✨'{self.catWord}'✨"
226+
227+
228+
cat2 = MagicalCat("Mistoffelees")
229+
print(cat2.speak())
230+

pythonCheatsheet.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,31 @@ Not so helpful! So we can add a `__str__ ` method that turns it into a more usef
308308
return f"{self.name}, a {self.mood} cat"
309309
```
310310

311+
311312
```
312313
Bustopher, a happy cat
313314
Grizabella, a sad cat
314315
```
316+
317+
You can also *inherit* from existing classes
318+
```
319+
320+
class MagicalCat(Cat):
321+
catWord = "abracadabra"
322+
323+
def __init__(self, name):
324+
super().__init__(name)
325+
def speak(self):
326+
return f"{self.name} says ✨'{self.catWord}'✨"
327+
328+
329+
cat2 = MagicalCat("Mistoffelees")
330+
print(cat2.speak())
331+
```
332+
333+
```
334+
Grizabella says 'meow'
335+
Mistoffelees says ✨'abracadabra'✨
336+
```
337+
338+

pythonCheatsheet.pdf

8.37 KB
Binary file not shown.

0 commit comments

Comments
 (0)