-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmagicMethods.py
More file actions
45 lines (36 loc) · 1.37 KB
/
magicMethods.py
File metadata and controls
45 lines (36 loc) · 1.37 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
# copy is a built in module that creates new copies. This is used in the following __mul__ method. Without it, you are not creating space for new copies
from copy import copy
class Human:
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
def __repr__(self):
return f"Human named {self.first} {self.last}"
# If you want to get the length of your Human instance, you need to add the method __len__ here
# This is example is a bit odd. So the len here means print the age. len of life?
def __len__(self):
return self.age
# hand argument like so: j + k
def __add__(self, other):
# check that the argument handed to this method is an instance of the class Human. Otherwise don't run the method.
if isinstance(other, Human):
return Human(first="Newborn", last=self.last, age=0)
# normally you would raise a typeerror here
return "You can't add that."
# cloning humans using multiplication
def __mul__(self, other):
# check that the second argument passing is an integer
if isinstance(other, int):
return [copy(self) for i in range(other)]
# normally you would raise a typeerror here
return "You are cloning humans"
j = Human("Jorgen", "Jergens", 89)
k = Human("Kervel", "Kringle", 67)
print(j)
print(len(j))
print(j + k)
# change the name of the second clone to "John"
twins = j * 2
twins[1].first = "John"
print(twins)