-
Notifications
You must be signed in to change notification settings - Fork 0
/
PYTHON-COLT-PART-2.txt
728 lines (462 loc) · 15.2 KB
/
PYTHON-COLT-PART-2.txt
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
PART 2 PYTHON
DEBUGGING AND ERROR HANDLING
- COMMON ERRORS:
- SyntaxError - typo
- NameError - variable is not defined
- TypeError - mismatch of data types
- IndexError - accessing an invalid index in a list, tuple
- KeyError - when accessing an invalid key
- ValueError - if a function receives an argument an inappropriate value
- AttributeError - trying to use a method that is not valid
- RAISING OUR OWN ERRORS, CREATING CUSTOM MESSAGE
- raise SyntaxError("Putang ina mo ang bobo mo po")
- def colorize(text, color):
colors = ("red", "orange", "black")
if type(color) is not str:
raise TypeError("Color must be a str data type")
if type(text) is not str:
raise TypeError("Text must be a str data type")
if color not in colors:
raise ValueError("Color is invalid color")
print(f"Printed text {text} in {color}")
- colorize("hello", "brown")
- TRY AND EXCEPT BLOCKS
- try:
add_numbers
except:
print("This is try and except shit")
- def get(d,key):
try:
return d[key]
except KeyError:
return None
- d = {"name": "Ricky"}
- print(get(d, "city"))
- d["city"]
- TRY, EXCEPT, ELSE, FINALLY
- while True:
try:
num = int(input("please enter a number: "))
except ValueError:
print("That's not a number!")
else:
print("Good job, you entered a number!")
break
finally:
print("RUNS NO MATTER WHAT!")
- print("REST OF GAME LOGIC RUNS!")
- DEBUGGING WITH PDB
- FIRST EXAMPLE:
# import pdb
# first = "First"
# second = "Second"
# pdb.set_trace()
# result = first + second
# third = "Third"
# result += third
# print(result)
# Be careful with variable names!
def add_numbers(a, b, c, d):
import pdb; pdb.set_trace()
return a + b + c + d
add_numbers(1,2,3,4)
# ===================
# NOTES NOTES NOTES
# ===================
# import pdb
# pdb.set_trace()
# Also commonly on one line:
# import pdb; pdb.set_trace()
# Common PDB Commands:
# l (list)
# n (next line)
# p (print)
# c (continue - finishes debugging)
MODULES
*** built-in python modules - go to python website
- import random
- print(random.choice(["apple", "banana", "cherry", "durian"]))
- print(random.randint(1, 10))
- import random as r
- print(r.choice(["apple", "banana", "cherry", "durian"]))
- print(r.randint(1, 10))
- from random import choice, randint
- print(choice(["apple", "banana", "cherry", "durian"]))
- print(randint(1,100))
- from random import choice as pick, randint as magic_number_chooser
- print(pick(["apple", "banana", "cherry", "durian"]))
- print(magic_number_chooser(1,100))
*** custom modules
- create 2 python files
- import the file1 to file2
import file1 # put this inside file2
- run the functions declared inside file1
print(file1.greet()) # run this inside file2
- from file1 import greet as g # other way of importing
*** installing external modules - go back here 22 - 220
- go to https://pypi.org/ for list of modules available, pip
- installing the termcolor package
python -m pip install termcolor # command to install a module
help(termcolor) # to see the available functions and options
- import termcolor after installing it in the command line
from termcolor import colored
t = colored("This is it! You're progressing", color="blue", on_color="on_magenta", attrs=["blink"])
print(t)
- go back to 221 for using the termcolor, pyfiglet package
*** autopep8 package
- used to clean up your code, to fix the code
- go back to 222 to learn autopep8 package
*** the __name__ variable
- to show if the function is in the main python file or imported python file on the main file
- it shows __main__ if its executed in the main python file
- if the file is the main file being run, its value is __main__
- if __name__ == "__main__" # to make sure that it only runs on the main file
23 Making http requests with python (OPTIONAL) let's skip this shit for now
OOP
- class is a blueprint for object
- object is an instance of a class
help(list) # to see the other methods of this list class
- encapsulation is the grouping of public and private attributes and methods into a programmatic class, making abstraction possible
- abstraction is exposing only relevant data in a class interface, hiding private attributes and methods from users
- creating a class
class User:
pass
# creating a class instance
user1 = User()
print(type(user1))
*** adding instance attributes
class User:
def __init__(self, first, last, age): # 3 instance attributes
self.name = first
self.last = last
self.age = age
user1 = User("Rommel", "Pogi", 29)
print(user1.name)
*** dunder methods and name mangling
- single underscore
- _name = it's a private variable
- double underscore
- it activates name mingling
- uses to avoid naming conflicts in subclasses
class User:
def __init__(self, first, last, age):
self.name = first
self.last = last
self.age = age
self.__msg = "this is name mingling" # with 2 underscores
user1 = User("Rommel", "Pogi", 29)
print(user1._User__msg) # to activate an attribute with 2 underscores
- 3 underscores
- only used on python specific methods
*** adding instance methods
# A User class with both instance attributes and instance methods
class User:
def __init__(self, first, last, age): # instance attributes
self.first = first
self.last = last
self.age = age
def full_name(self): # instance methods
return f"{self.first} {self.last}"
def initials(self): # instance methods
return f"{self.first[0]}.{self.last[0]}."
def likes(self, thing): # instance methods
return f"{self.first} likes {thing}"
def is_senior(self): # instance methods
return self.age >= 65
def birthday(self): # instance methods
self.age += 1
return f"Happy {self.age}th, {self.first}"
user1 = User("Joe", "Smith", 68)
user2 = User("Blanca", "Lopez", 41)
print(user1.likes("Ice Cream")) # invoking the instance methods
print(user2.likes("Chips")) # invoking the instance methods
print(user2.initials())
print(user1.initials())
print(user2.is_senior())
print(user1.age) #Print age before we update it
print(user1.birthday()) #updates age
print(user1.age) #Print new value of age
*** class attributes
# A User class with both a class attribute
class User:
active_users = 0 # this is the class attribute
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
User.active_users += 1 # manipulating class attribute
def logout(self):
User.active_users -= 1 # manipulating class attribute
return f"{self.first} has logged out"
def full_name(self):
return f"{self.first} {self.last}"
def initials(self):
return f"{self.first[0]}.{self.last[0]}."
def likes(self, thing):
return f"{self.first} likes {thing}"
def is_senior(self):
return self.age >= 65
def birthday(self):
self.age += 1
return f"Happy {self.age}th, {self.first}"
print(User.active_users)
user1 = User("Joe", "Smith", 68)
user2 = User("Blanca", "Lopez", 41)
print(User.active_users)
print(user2.logout())
print(User.active_users)
*** class methods
# A User class with both instance attributes and instance methods
class User:
active_users = 0
@classmethod # class method
def display_active_users(cls):
return f"There are currently {cls.active_users} active users"
@classmethod
def from_string(cls, data_str):
first,last,age = data_str.split(",")
return cls(first, last, int(age))
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
User.active_users += 1
def logout(self):
User.active_users -= 1
return f"{self.first} has logged out"
def full_name(self):
return f"{self.first} {self.last}"
def initials(self):
return f"{self.first[0]}.{self.last[0]}."
def likes(self, thing):
return f"{self.first} likes {thing}"
def is_senior(self):
return self.age >= 65
def birthday(self):
self.age += 1
return f"Happy {self.age}th, {self.first}"
# user1 = User("Joe", "Smith", 68)
# user2 = User("Blanca", "Lopez", 41)
# print(User.display_active_users())
# user1 = User("Joe", "Smith", 68)
# user2 = User("Blanca", "Lopez", 41)
# print(User.display_active_users())
*** another way of creating instance using a classmethod
# A User class with both instance attributes and instance methods
class User:
active_users = 0
@classmethod
def display_active_users(cls):
return f"There are currently {cls.active_users} active users"
@classmethod # class method used for creating another instance
def from_string(cls, data_str):
first,last,age = data_str.split(",")
return cls(first, last, int(age))
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
User.active_users += 1
def logout(self):
User.active_users -= 1
return f"{self.first} has logged out"
def full_name(self):
return f"{self.first} {self.last}"
def initials(self):
return f"{self.first[0]}.{self.last[0]}."
def likes(self, thing):
return f"{self.first} likes {thing}"
def is_senior(self):
return self.age >= 65
def birthday(self):
self.age += 1
return f"Happy {self.age}th, {self.first}"
tom = User.from_string("Tom,Jones,89") # invoked the class method to create a new instance
print(tom.first)
print(tom.full_name())
print(tom.birthday())
*** the __repr__ method
- used to show a definition of an instance
class User:
active_users = 0
@classmethod
def display_active_users(cls):
return f"There are currently {cls.active_users} active users"
@classmethod # class method used for creating another instance
def from_string(cls, data_str):
first,last,age = data_str.split(",")
return cls(first, last, int(age))
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
User.active_users += 1
def __repr__(self): # to declare a __repr__
return {'name':self.name, 'age':self.age}
def logout(self):
User.active_users -= 1
return f"{self.first} has logged out"
def full_name(self):
return f"{self.first} {self.last}"
def initials(self):
return f"{self.first[0]}.{self.last[0]}."
def likes(self, thing):
return f"{self.first} likes {thing}"
def is_senior(self):
return self.age >= 65
def birthday(self):
self.age += 1
return f"Happy {self.age}th, {self.first}"
tom = User.from_string("Tom,Jones,89") # invoked the class method to create a new instance
print(tom.first)
print(tom.full_name())
print(tom.birthday())
print(tom) # to invoke what is the string declared in the repr
25 DECK OF CARD EXERCISE - GO BACK HERE
OOP part 2
*** inheritance and objectives
class Animal:
cool = True
def make_sound(self, sound):
print(f"this animal says {sound}")
# Cat class inherits from Animal
class Cat(Animal):
pass
# Make a new cat instance
blue = Cat()
# Because of inheritance, a Cat has access to:
blue.make_sound("Meow")
print(blue.cool)
#blue is both a Cat and Animal (and base object)
print(isinstance(blue, Cat))
print(isinstance(blue, Animal))
print(isinstance(blue, object))
*** properties
class Person:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def full(self):
return f"{self.first} {self.last}"
@full.setter
def full(self, el):
self.first, self.last = el.split(' ')
rommel = Person("Rommel", "Torquator")
rommel.full = "Toshi Pogi"
print(rommel.full)
*** super().__init__()
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
class Tiger(Animal):
def __init__(self, name, food, likes):
super().__init__(name, species="Tiger")
self.food = food
self.likes = likes
kobe = Tiger("Kobe", "Cat meat", "Kill")
print(kobe.food)
jordan = Animal("Jordan", "Shark")
print(jordan.species)
*** find inheritance complex example online
*** multiple inheritance
class Aquatic:
def __init__(self,name):
print("AQUATIC INIT!")
self.name = name
def swim(self):
return f"{self.name} is swimming"
def greet(self):
return f"I am {self.name} of the sea!"
class Ambulatory:
def __init__(self,name):
print("AMBULATORY INIT!")
self.name = name
def walk(self):
return f"{self.name} is walking"
def greet(self):
return f"I am {self.name} of the land!"
class Penguin(Ambulatory, Aquatic):
def __init__(self,name):
print("PENGUIN INIT!")
super().__init__(name=name)
# Ambulatory.__init__(self,name=name)
# Aquatic.__init__(self, name=name)
jaws = Aquatic("Jaws")
lassie = Ambulatory("Lassie")
captain_cook = Penguin("Captain Cook")
print(captain_cook.swim())
print(captain_cook.walk())
print(captain_cook.greet())
print(f"captain_cook is instance of Penguin: {isinstance(captain_cook, Penguin)}")
print(f"captain_cook is instance of Aquatic: {isinstance(captain_cook, Aquatic)}")
print(f"captain_cook is instance of Ambulatory: {isinstance(captain_cook, Ambulatory)}")
*** method resolution order (MRO)
class Aquatic:
def __init__(self,name):
print("AQUATIC INIT!")
self.name = name
def swim(self):
return f"{self.name} is swimming"
def greet(self):
return f"I am {self.name} of the sea!"
class Ambulatory:
def __init__(self,name):
print("AMBULATORY INIT!")
self.name = name
def walk(self):
return f"{self.name} is walking"
def greet(self):
return f"I am {self.name} of the land!"
class Penguin(Ambulatory, Aquatic):
def __init__(self,name):
print("PENGUIN INIT!")
super().__init__(name=name)
# Ambulatory.__init__(self,name=name)
# Aquatic.__init__(self, name=name)
jaws = Aquatic("Jaws")
lassie = Ambulatory("Lassie")
captain_cook = Penguin("Captain Cook")
print(captain_cook.swim())
print(captain_cook.walk())
print(captain_cook.greet())
print(f"captain_cook is instance of Penguin: {isinstance(captain_cook, Penguin)}")
print(f"captain_cook is instance of Aquatic: {isinstance(captain_cook, Aquatic)}")
print(f"captain_cook is instance of Ambulatory: {isinstance(captain_cook, Ambulatory)}")
#print(Penguin.__mro__)
#print(Penguin.mro())
print(help(Penguin))
*** polymorphism
- method overriding
- refers to a programming language's ability to process objects differently depending on their data type or class
- The word polymorphism means having many forms
- In programming, if a variable can hold more than one type of value, then that's a kind of polymorphism
*** special __magic__ methods, dunder methods, special methods
class Employee:
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
def __repr__(self): # magic method
return "Employee('{}', '{}', {})".format(self.first, self.last, self.pay)
def __str__(self): # magic method
return '{} - {}'.format(self.fullname(), self.email)
def __add__(self, other): # magic method
return self.pay + other.pay
def __len__(self): # magic method
return len(self.fullname())
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)
# print(repr(emp_1))
# print(str(emp_2))
# print(emp_1 + emp_2) # add method
print(len(emp_1)) # len method
- isinstance(rommel, Human) # this is useful, it return true or false
- there are different magic methods, just seach it online