-
Notifications
You must be signed in to change notification settings - Fork 0
/
Object-Oriented_Programming_in_Python.py
824 lines (590 loc) · 18 KB
/
Object-Oriented_Programming_in_Python.py
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
####################
# OOP Fundamentals #
####################
### Exploring object interface
# Print the mystery employee's name
print(mystery.name)
# Print the mystery employee's salary
print(mystery.salary)
# Give the mystery employee a raise of $2500
mystery.give_raise(2500)
# Print the salary again
print(mystery.salary)
### Create a class
# Create an empty class Employee
class Employee:
pass
# Create an object emp of class Employee
emp = Employee()
# Include a set_name method
class Employee:
def set_name(self, new_name):
self.name = new_name
# Create an object emp of class Employee
emp = Employee()
# Use set_name() on emp to set the name of emp to 'Korel Rossi'
emp.set_name('Korel Rossi')
# Print the name of emp
print(emp.name)
class Employee:
def set_name(self, new_name):
self.name = new_name
# Add set_salary() method
def set_salary(self, new_salary):
self.salary = new_salary
# Create an object emp of class Employee
emp = Employee()
# Use set_name to set the name of emp to 'Korel Rossi'
emp.set_name('Korel Rossi')
# Set the salary of emp to 50000
emp.set_salary(50000)
### Using attributes in class definition
# 1
class Employee:
def set_name(self, new_name):
self.name = new_name
def set_salary(self, new_salary):
self.salary = new_salary
emp = Employee()
emp.set_name('Korel Rossi')
emp.set_salary(50000)
# Print the salary attribute of emp
print(emp.salary)
# Increase salary of emp by 1500
emp.salary = emp.salary + 1500
# Print the salary attribute of emp again
print(emp.salary)
# 2
class Employee:
def set_name(self, new_name):
self.name = new_name
def set_salary(self, new_salary):
self.salary = new_salary
# Add a give_raise() method with raise amount as a parameter
def give_raise(self, raise_amount):
self.salary = self.salary + raise_amount
emp = Employee()
emp.set_name('Korel Rossi')
emp.set_salary(50000)
print(emp.salary)
emp.give_raise(1500)
print(emp.salary)
# 3
class Employee:
def set_name(self, new_name):
self.name = new_name
def set_salary(self, new_salary):
self.salary = new_salary
def give_raise(self, amount):
self.salary = self.salary + amount
# Add monthly_salary method that returns 1/12th of salary attribute
def monthly_salary(self):
return self.salary / 12
emp = Employee()
emp.set_name('Korel Rossi')
emp.set_salary(50000)
# Get monthly salary of emp and assign to mon_sal
mon_sal = emp.monthly_salary()
# Print mon_sal
print(mon_sal)
### Add a class constructor
# 1
class Employee:
# Create __init__() method
def __init__(self, name, salary=0):
# Create the name and salary attributes
self.name = name
self.salary = salary
# From the previous lesson
def give_raise(self, amount):
self.salary += amount
def monthly_salary(self):
return self.salary/12
emp = Employee("Korel Rossi")
print(emp.name)
print(emp.salary)
# 2
class Employee:
def __init__(self, name, salary=0):
self.name = name
# Modify code below to check if salary is positive
if salary > 0:
self.salary = salary
else:
self.salary = 0
print("Invalid salary!")
# ...Other methods omitted for brevity ...
emp = Employee("Korel Rossi", -1000)
print(emp.name)
print(emp.salary)
# 3
# Import datetime from datetime
from datetime import datetime
class Employee:
def __init__(self, name, salary=0):
self.name = name
if salary > 0:
self.salary = salary
else:
self.salary = 0
print("Invalid salary!")
# Add the hire_date attribute and set it to today's date
self.hire_date = datetime.today()
# ...Other methods omitted for brevity ...
emp = Employee("Korel Rossi", -1000)
print(emp.name)
print(emp.salary)
### Write a class from scratch
# Write the class Point as outlined in the instructions
import numpy as np
class Point:
def __init__(self,x=0.0,y=0.0):
self.x = x
self.y = y
def distance_to_origin(self):
return np.sqrt(self.x**2 + self.y**2)
def reflect(self, axis):
if axis == "x":
self.y = - self.y
elif axis == "y":
self.x = -self.x
else:
print("Error!")
################################
# Inheritance and Polymorphism #
################################
### Class-level attributes
# 1
# Create a Player class
class Player:
MAX_POSITION = 10
def __init__(self):
self.position = 0
# Print Player.MAX_POSITION
print(Player.MAX_POSITION)
# Create a player p and print its MAX_POSITITON
p = Player()
print(p.MAX_POSITION)
# 2
class Player:
MAX_POSITION = 10
def __init__(self):
self.position = 0
# Add a move() method with steps parameter
def move(self, steps):
if self.position + steps < Player.MAX_POSITION:
self.position += steps
else:
self.position = Player.MAX_POSITION
# This method provides a rudimentary visualization in the console
def draw(self):
drawing = "-" * self.position + "|" +"-"*(Player.MAX_POSITION - self.position)
print(drawing)
p = Player(); p.draw()
p.move(4); p.draw()
p.move(5); p.draw()
p.move(3); p.draw()
### Changing class attributes
# 1
# Create Players p1 and p2
p1 = Player()
p2 = Player()
print("MAX_SPEED of p1 and p2 before assignment:")
# Print p1.MAX_SPEED and p2.MAX_SPEED
print(p1.MAX_SPEED)
print(p2.MAX_SPEED)
# Assign 7 to p1.MAX_SPEED
p1.MAX_SPEED = 7
print("MAX_SPEED of p1 and p2 after assignment:")
# Print p1.MAX_SPEED and p2.MAX_SPEED
print(p1.MAX_SPEED)
print(p2.MAX_SPEED)
print("MAX_SPEED of Player:")
# Print Player.MAX_SPEED
print(Player.MAX_SPEED)
# 2
# Create Players p1 and p2
p1, p2 = Player(), Player()
print("MAX_SPEED of p1 and p2 before assignment:")
# Print p1.MAX_SPEED and p2.MAX_SPEED
print(p1.MAX_SPEED)
print(p2.MAX_SPEED)
# ---MODIFY THIS LINE---
Player.MAX_SPEED = 7
print("MAX_SPEED of p1 and p2 after assignment:")
# Print p1.MAX_SPEED and p2.MAX_SPEED
print(p1.MAX_SPEED)
print(p2.MAX_SPEED)
print("MAX_SPEED of Player:")
# Print Player.MAX_SPEED
print(Player.MAX_SPEED)
### Alternative constructors
# 1
class BetterDate:
# Constructor
def __init__(self, year, month, day):
# Recall that Python allows multiple variable assignments in one line
self.year, self.month, self.day = year, month, day
# Define a class method from_str
@classmethod
def from_str(cls, datestr):
# Split the string at "-" and convert each part to integer
parts = datestr.split("-")
year, month, day = int(parts[0]), int(parts[1]), int(parts[2])
# Return the class instance
return BetterDate(year, month, day)
bd = BetterDate.from_str('2020-04-30')
print(bd.year)
print(bd.month)
print(bd.day)
# 2
# import datetime from datetime
from datetime import datetime
class BetterDate:
def __init__(self, year, month, day):
self.year, self.month, self.day = year, month, day
@classmethod
def from_str(cls, datestr):
year, month, day = map(int, datestr.split("-"))
return cls(year, month, day)
# Define a class method from_datetime accepting a datetime object
@classmethod
def from_datetime(cls, datetime):
year = datetime.year
month = datetime.month
day = datetime.day
return cls(year, month, day)
# You should be able to run the code below with no errors:
today = datetime.today()
bd = BetterDate.from_datetime(today)
print(bd.year)
print(bd.month)
print(bd.day)
### Create a subclass
# 1
class Employee:
MIN_SALARY = 30000
def __init__(self, name, salary=MIN_SALARY):
self.name = name
if salary >= Employee.MIN_SALARY:
self.salary = salary
else:
self.salary = Employee.MIN_SALARY
def give_raise(self, amount):
self.salary += amount
# Define a new class Manager inheriting from Employee
class Manager(Employee):
pass
# Define a Manager object
mng = Manager('Debbie Lashko',86500)
# Print mng's name
print(mng.name)
# 2
class Employee:
MIN_SALARY = 30000
def __init__(self, name, salary=MIN_SALARY):
self.name = name
if salary >= Employee.MIN_SALARY:
self.salary = salary
else:
self.salary = Employee.MIN_SALARY
def give_raise(self, amount):
self.salary += amount
# MODIFY Manager class and add a display method
class Manager(Employee):
def display(self):
print('Manager ' + self.name)
mng = Manager("Debbie Lashko", 86500)
print(mng.name)
# Call mng.display()
mng.display()
### Method inheritance
# 1
class Employee:
def __init__(self, name, salary=30000):
self.name = name
self.salary = salary
def give_raise(self, amount):
self.salary += amount
class Manager(Employee):
# Add a constructor
def __init__(self, name, salary=50000, project = None):
# Call the parent's constructor
Employee.__init__(self, name, salary)
# Assign project attribute
self.project = project
def display(self):
print("Manager ", self.name)
# 2
class Employee:
def __init__(self, name, salary=30000):
self.name = name
self.salary = salary
def give_raise(self, amount):
self.salary += amount
class Manager(Employee):
def display(self):
print("Manager ", self.name)
def __init__(self, name, salary=50000, project=None):
Employee.__init__(self, name, salary)
self.project = project
# Add a give_raise method
def give_raise(self,amount,bonus=1.05):
Employee.give_raise(self,amount*bonus)
mngr = Manager("Ashta Dunbar", 78500)
mngr.give_raise(1000)
print(mngr.salary)
mngr.give_raise(2000, bonus=1.03)
print(mngr.salary)
### Inheritance of class attributes
# Create a Racer class and set MAX_SPEED to 5
class Racer(Player):
MAX_SPEED = 5
# Create a Player and a Racer objects
p = Player()
r = Racer()
print("p.MAX_SPEED = ", p.MAX_SPEED)
print("r.MAX_SPEED = ", r.MAX_SPEED)
print("p.MAX_POSITION = ", p.MAX_POSITION)
print("r.MAX_POSITION = ", r.MAX_POSITION)
### Customizing a DataFrame
# 1
# Import pandas as pd
import pandas as pd
# Define LoggedDF inherited from pd.DataFrame and add the constructor
class LoggedDF(pd.DataFrame):
def __init__(self, *args, **kwargs):
pd.DataFrame.__init__(self, *args, **kwargs)
self.created_at = datetime.today()
ldf = LoggedDF({"col1": [1,2], "col2": [3,4]})
print(ldf.values)
print(ldf.created_at)
# 2
# Import pandas as pd
import pandas as pd
# Define LoggedDF inherited from pd.DataFrame and add the constructor
class LoggedDF(pd.DataFrame):
def __init__(self, *args, **kwargs):
pd.DataFrame.__init__(self, *args, **kwargs)
self.created_at = datetime.today()
def to_csv(self, *args, **kwargs):
# Copy self to a temporary DataFrame
temp = self.copy()
# Create a new column filled with self.created_at
temp["created_at"] = self.created_at
# Call pd.DataFrame.to_csv on temp, passing in *args and **kwargs
pd.DataFrame.to_csv(temp, *args, **kwargs)
####################################
# Integrating with Standard Python #
####################################
### Overloading equality
class BankAccount:
# MODIFY to initialize a number attribute
def __init__(self, number,balance=0):
self.balance = balance
self.number = number
def withdraw(self, amount):
self.balance -= amount
# Define __eq__ that returns True if the number attributes are equal
def __eq__(self, other):
return self.number == other.number
# Create accounts and compare them
acct1 = BankAccount(123, 1000)
acct2 = BankAccount(123, 1000)
acct3 = BankAccount(456, 1000)
print(acct1 == acct2)
print(acct1 == acct3)
### Checking class equality
class BankAccount:
def __init__(self, number, balance=0):
self.number, self.balance = number, balance
def withdraw(self, amount):
self.balance -= amount
# MODIFY to add a check for the type()
def __eq__(self, other):
return (self.number == other.number and type(self) == type(other))
acct = BankAccount(873555333)
pn = Phone(873555333)
print(acct == pn)
### String representation of objects
# 1
class Employee:
def __init__(self, name, salary=30000):
self.name, self.salary = name, salary
# Add the __str__() method
def __str__(self):
Employee.str= """
Employee name: {name}
Employee salary: {salary}
""".format(name = self.name, salary = self.salary)
return Employee.str
emp1 = Employee("Amar Howard", 30000)
print(emp1)
emp2 = Employee("Carolyn Ramirez", 35000)
print(emp2)
# 2
class Employee:
def __init__(self, name, salary=30000):
self.name, self.salary = name, salary
def __str__(self):
s = "Employee name: {name}\nEmployee salary: {salary}".format(name=self.name, salary=self.salary)
return s
# Add the __repr__method
def __repr__(self):
return 'Employee("{name}", {salary})'.format(name=self.name, salary=self.salary)
emp1 = Employee("Amar Howard", 30000)
print(repr(emp1))
emp2 = Employee("Carolyn Ramirez", 35000)
print(repr(emp2))
### Catching exceptions
# MODIFY the function to catch exceptions
def invert_at_index(x, ind):
try:
return 1/x[ind]
except ZeroDivisionError:
print("Cannot divide by zero!")
except IndexError:
print("Index out of range!")
a = [5,6,0,7]
# Works okay
print(invert_at_index(a, 1))
# Potential ZeroDivisionError
print(invert_at_index(a, 2))
# Potential IndexError
print(invert_at_index(a, 5))
### Custom exceptions
# 1
# Define SalaryError inherited from ValueError
class SalaryError(ValueError):
pass
# Define BonusError inherited from SalaryError
class BonusError(SalaryError):
pass
# 2
class SalaryError(ValueError): pass
class BonusError(SalaryError): pass
class Employee:
MIN_SALARY = 30000
MAX_RAISE = 5000
def __init__(self, name, salary = 30000):
self.name = name
# If salary is too low
if salary < MIN_SALARY:
# Raise a SalaryError exception
raise ValueError("Salary is too low!")
self.salary = salary
# 3
class SalaryError(ValueError): pass
class BonusError(SalaryError): pass
class Employee:
MIN_SALARY = 30000
MAX_BONUS = 5000
def __init__(self, name, salary = 30000):
self.name = name
if salary < Employee.MIN_SALARY:
raise SalaryError("Salary is too low!")
self.salary = salary
# Rewrite using exceptions
def give_bonus(self, amount):
if amount > Employee.MAX_BONUS:
raise ValueError("The bonus amount is too high!")
elif self.salary + amount < Employee.MIN_SALARY:
raise ValueError("The salary after bonus is too low!")
else:
self.salary += amount
##################################
# Best Practices of Class Design #
##################################
### Square and rectangle
# 1
# Define a Rectangle class
class Rectangle:
def __init__(self,h,w):
self.h = h
self.w = w
# Define a Square class
class Square(Rectangle):
def __init__(self,w):
self.w = w
self.h = w
# 2
class Rectangle:
def __init__(self, w,h):
self.w, self.h = w,h
# Define set_h to set h
def set_h(self, h):
self.h = h
# Define set_w to set w
def set_w(self, w):
self.w = w
class Square(Rectangle):
def __init__(self, w):
self.w, self.h = w, w
# Define set_h to set w and h
def set_h(self, h):
self.h = h
self.w = h
# Define set_w to set w and h
def set_w(self, w):
self.w = w
self.h = w
### Using internal attributes
# Add class attributes for max number of days and months
class BetterDate:
_MAX_DAYS = 30
_MAX_MONTHS = 12
def __init__(self, year, month, day):
self.year, self.month, self.day = year, month, day
@classmethod
def from_str(cls, datestr):
year, month, day = map(int, datestr.split("-"))
return cls(year, month, day)
# Add _is_valid() checking day and month values
def _is_valid(self):
return (self.day <= BetterDate._MAX_DAYS) and \
(self.month <= BetterDate._MAX_MONTHS)
bd1 = BetterDate(2020, 4, 30)
print(bd1._is_valid())
bd2 = BetterDate(2020, 6, 45)
print(bd2._is_valid())
### Create and set properties
class Customer:
def __init__(self, name, new_bal):
self.name = name
if new_bal < 0:
raise ValueError("Invalid balance!")
self._balance = new_bal
# Add a decorated balance() method returning _balance
@property
def balance(self):
return self._balance
# Add a setter balance() method
@balance.setter
def balance(self, new_bal):
# Validate the parameter value
if new_bal < 0:
raise ValueError("Invalid balance!")
self._balance = new_bal
print("Setter method called")
# Create a Customer
cust = Customer("Belinda Lutz", 2000)
cust.balance = 3000
print(cust.balance)
### Read-only properties
import pandas as pd
from datetime import datetime
# MODIFY the class to use _created_at instead of created_at
class LoggedDF(pd.DataFrame):
def __init__(self, *args, **kwargs):
pd.DataFrame.__init__(self, *args, **kwargs)
self._created_at = datetime.today()
def to_csv(self, *args, **kwargs):
temp = self.copy()
temp["created_at"] = self._created_at
pd.DataFrame.to_csv(temp, *args, **kwargs)
# Add a read-only property: _created_at
@property
def created_at(self):
return self._created_at
# Instantiate a LoggedDF called ldf
ldf = LoggedDF({"col1": [1,2], "col2":[3,4]})