-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclasses_intro3.py
More file actions
156 lines (116 loc) · 4.23 KB
/
classes_intro3.py
File metadata and controls
156 lines (116 loc) · 4.23 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""
Now we've learned a few things about classes. Specifically
- How to declare one
- How to create one
- Class methods ALWAYS take self as the first parameter
- How to add members and intialize them with __init__
Now some more extended functionality. In particular how to use
some other overrides in Python classes, and further still, how
a class can derive from another, which is called inheritance.
"""
"""
Lets continue with the classes we already defined in the first class
on classes, specifically Dog and DogPound.
Dog remains unchanged, but look at DogPound with some pretty specific changes.
1. __add__ overrides the default Python implementation
2. __str__ which is called every time the object is accessed as a string
"""
class Dog:
def __init__(self, dog_name, dog_sound):
self.name = dog_name
self.sound = dog_sound
def __str__(self):
""" This overrides the base functionality
and returns a custom string when we want
to print out a Dog class"""
return "{} says {}".format(
self.name,
self.sound
)
print(Dog("Joel", "woofwoof"))
input("Next update DogPound")
class DogPound:
def __init__(self):
self.dogs_in_pound = []
def __add__(self, dog):
""" Overrides the default python adding
of two objects, and now you can add a dog
to the pound like this
pound += dog
"""
self.dogs_in_pound.append(dog)
return self
def __str__(self):
""" Override str just like in dog """
return_value = ""
for dog in self.dogs_in_pound:
return_value += str(dog) + "\n"
return return_value
"""
Now lets test this out...very different from the last one.
Notice we can use += on the pound to add a dog and we don't
need to do anything to print out the pound as a string we
just access it with print, which will call __str__
"""
pound = DogPound()
pound += Dog("Rover", "bark")
pound += Dog("Biff", "yelp")
print("Pound Content:\n{}".format(pound))
input("\nNext try inheritance")
"""
Ok, mind blown right? But like one of those TV adds....
"Wait, theres more!"
Inheritance, this is how a lot of programming problems are solved.
We use something called a "base" class that holds common functionality
of two similar things.
For this example, lets keep going with dogs. We can have big dogs and
little dogs..
Inheritance is declared with the class declaration as
class ClassName(DerivingClass)
Now your class has all the same functionality of the base class.
"""
class BigDog(Dog):
def __init__(self, name, sound):
""" Because Dog has a constructor that takes arguments
we have to call it's constructor.
We do that by using super() which finds the deriving class
and then we call it's __init__ directly.
The only thing we change is the sound, big dogs are loud so
we will upper case whatever it says.
"""
super().__init__(name, sound.upper())
"""
Now we'll do the following
- Create a BigDog
- Add it to the pound
- Print the pound
Note that we just add a big dog like a regular dog and the pound still
has everything we added before.
"""
bd = BigDog("Ralf", "bark")
pound += bd
print("Pound Content:\n{}".format(pound))
"""
BONUS - If time permits
We can also use a python function to determine if the object we have
is a type of object we want to work with.
That is 'isinstance' and we give it two arguments
1. The object we want to inspect
2. The type we are checking for
We can play with this using the dog pound - dogs_in_pound
NOTE: This is a really advanced idea, so it is totally fine if this
confuses you...some people in Computer Science programs struggle with
this....
"""
input("\nNow show the isinstance() functionality")
for dog in pound.dogs_in_pound:
print("{} is of type {}, and is instance of a dog? {}".format(
dog.name,
type(dog),
isinstance(dog, Dog)
))
"""
Takeaway - Ralf is a BigDog, but BigDog derives (inherits) from
Dog....so Ralf is a Dog after all because Dog is in the inheritance
chain.
"""