Skip to content

Commit 6a70de2

Browse files
named tuples section and exercises
1 parent 17e432e commit 6a70de2

14 files changed

Lines changed: 217 additions & 468 deletions

README.md

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -85,15 +85,10 @@ than complex*.
8585
## Frequently asked questions
8686

8787

88-
## Authors
88+
## Special thanks
8989

90-
I'm Akuli and I have written most of this tutorial, but these people
91-
have helped me with it:
92-
- [SpiritualForest](https://github.com/SpiritualForest): Lots of typing
93-
error fixes.
94-
- [theelous3](https://github.com/theelous3): Small improvements and fixes.
90+
Thanks to Akuli who wrote the most of this tutorial
9591

9692
***
9793

98-
9994
[List of contents](./README.md#list-of-contents)

advanced/answers.md

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,4 @@
11

22
***
33

4-
If you have trouble with this tutorial please [tell me about
5-
it](../contact-me.md) and I'll make this tutorial better. If you
6-
like this tutorial, please [give it a
7-
star](../README.md#how-can-i-thank-you-for-writing-and-sharing-this-tutorial).
8-
9-
You may use this tutorial freely at your own risk. See
10-
[LICENSE](../LICENSE).
11-
124
[List of contents](../README.md#list-of-contents)

advanced/classes.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -417,5 +417,5 @@ print("You entered " + word + ".")
417417
***
418418

419419

420-
[Previous](exceptions.md) | [Next](namded_tuples.md) |
420+
[Previous](exceptions.md) | [Next](named_tuples.md) |
421421
[List of contents](../README.md#basics)

advanced/classes2.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Class Inheritance
2+
3+
We demonstrate inheritance in a very simple example. We create a Person class with the two attributes "firstname" and "lastname". This class has only one method, the Name method, essentially a getter, but we don't have an attribute name. This method is a further example for a "getter", which creates an output by creating it from more than one private attribute. Name returns the concatenation of the first name and the last name of a person, separated by a space. It goes without saying that a useful person class would have additional attributes and further methods.
4+
5+
This chapter of our tutorial is about inheritance, so we need a class, which inherits from Person. So far employees are Persons in companies, even though they may not be treated as such in some firms. If we created an Employee class without inheriting from Person, we would have to define all the attributes and methods in the Employee class again. This means we would create a design and maybe even a data redundancy. With this in mind, we have to let Employee inherit from Person.
6+
7+
The syntax for a subclass definition looks like this:
8+
9+
10+
```python
11+
class DerivedClassName(BaseClassName):
12+
pass
13+
```
14+
15+
Of course, usually we will have an indented block with the class attributes and methods instead of merely a pass statement. The name BaseClassName must be defined in a scope containing the derived class definition. With all this said, we can implement our Person and Employee class:
16+
17+
```python
18+
class Person:
19+
20+
def __init__(self, first, last):
21+
self.firstname = first
22+
self.lastname = last
23+
24+
def Name(self):
25+
return self.firstname + " " + self.lastname
26+
27+
class Employee(Person):
28+
29+
def __init__(self, first, last, staffnum):
30+
Person.__init__(self,first, last)
31+
self.staffnumber = staffnum
32+
33+
def GetEmployee(self):
34+
return self.Name() + ", " + self.staffnumber
35+
36+
x = Person("Marge", "Simpson")
37+
y = Employee("Homer", "Simpson", "1007")
38+
```
39+
40+
Our program returns the following output:
41+
42+
```bash
43+
$ python person.py
44+
Marge Simpson
45+
Homer Simpson, 1007
46+
```
47+
48+
The `__init__` method of our Employee class explicitly invokes the `__init__method` of the Person class. We could have used super instead. `super().__init__(first, last)` is automatically replaced by a call to the superclasses method, in this case `__init__`:
49+
50+
````python
51+
def __init__(self, first, last, staffnum):
52+
super().__init__(first, last)
53+
self.staffnumber = staffnum
54+
````

advanced/magicmethods.md

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ class doesn't define anything else. For example, if we don't define an
3333
attributes by default. We'll learn more about this when we'll talk about
3434
[inheritance](classes2.md).
3535

36-
**TODO:** write a `classes2.md`.
3736

3837
## Custom length
3938

@@ -221,6 +220,89 @@ methods in things that other people will import and use in their
221220
projects, but `__repr__` methods aren't worth it for simple scripts that
222221
are not meant to be imported.
223222

223+
## Exercise
224+
225+
The class CardDeck below represents a pack
226+
of cards.
227+
Find out how to use magic methods so that the
228+
following three standard functions work:
229+
```
230+
>>> import random
231+
>>> deck = CardDeck()
232+
>>> len(deck)
233+
52
234+
>>> print(deck[0])
235+
2♠
236+
>>> print(deck[-1])
237+
A♣
238+
>>> random.choice(deck) in list(deck)
239+
True
240+
>>> random.shuffle(deck)
241+
```
242+
Tip:
243+
If you have lines in the docstring (this string) that look like interactive
244+
Python sessions, you can use the doctest module to run and test this code.
245+
Try: python3 -m doctest -v magic_methods.py
246+
See: https://docs.python.org/3/library/doctest.html
247+
248+
Credit to Luciano Ramalho and his excellent book Fluent Python, from which
249+
I stole this example.
250+
"""
251+
252+
```python
253+
class CardDeck:
254+
ranks = [str(n) for n in range(2, 11)] + ['J', 'Q', 'K', 'A']
255+
suits = '♠♡♢♣'
256+
257+
def __init__(self):
258+
self._cards = [
259+
rank + suit
260+
for suit in self.suits
261+
for rank in self.ranks
262+
]
263+
```
264+
265+
266+
Bonus exercise:
267+
268+
Polynomial class
269+
Create a class that represents polynomials. You may need to stretch your memory back to high school maths!
270+
A polynomial loks like
271+
`2(xx) - x + 7`
272+
And its essential features are the coefficients of each power of x
273+
in this example, power-2=2, power-1=-1, power-0=7
274+
Credit to Moshe Goldstein
275+
276+
```
277+
class Polynomial:
278+
def __init__(self, coefficients):
279+
pass # TODO
280+
281+
def __str__(self):
282+
pass # TODO
283+
284+
def __add__(self, poly):
285+
'''returns the result of adding poly from self'''
286+
pass # TODO
287+
288+
def __sub__(self, poly):
289+
'''returns the result of subtracting poly from self'''
290+
pass # TODO
291+
292+
def __mul__(self, poly):
293+
'''multiply two polynomials'''
294+
pass # TODO
295+
296+
def value(self, x):
297+
'''returns the value of the polynomial at point x'''
298+
pass # TODO
299+
300+
def derivative(self):
301+
'''returns the derivate of the polynomial'''
302+
pass # TODO
303+
```
304+
305+
224306
## Summary
225307

226308
- Magic methods define what instances of a class can do and how, like

advanced/modules.md

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -487,8 +487,6 @@ section at the bottom.
487487
- Python comes with many modules, and we can install even more modules
488488
if we want to.
489489

490-
**TODO:** exercises
491-
492490
***
493491

494492

0 commit comments

Comments
 (0)