forked from rudrasingh21/Python
/
Python Class.py
657 lines (436 loc) · 15.9 KB
/
Python Class.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
------
CLASS:--
------
1) Class is a blueprint for creating instances.
2) Here each unique employee we will create, as a instance of this class.
3) We also have Class veriable. AND Instance variable.
------
Object :--
------
1) Object is one of instances of the class.
2) Which can perform the functionalities ,which are defined in the class.
------
self :--
------
1) self represents the instance of the class.
2) By using the "self" keyword we can access the attributes and methods of the class in python.
------
__init__ :--
------
The __init__ function is called a constructor, or initializer, and is automatically called
when you create a new instance of a class. Within that function, the newly created object
is assigned to the parameter self.
Please check blog:-
https://stackoverflow.com/questions/8609153/why-do-we-use-init-in-python-classes#
------------------------
Creating an empty class:-
------------------------
class Employee:
pass
NOTE:- The pass statement is a null operation; nothing happens when it executes.
The pass is also useful in places where your code will eventually go, but has not been written yet.
It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:
def f(arg): pass # a function that does nothing (yet)
class C: pass # a class with no methods (yet)
------------------------
Creating Instances of Employee class:-
------------------------
emp_1 = Employee()
emp_2 = Employee()
---> emp_1 and emp_2 are the instances of the class.
Let's Print:-
>>> print(emp_1)
<__main__.Employee instance at 0x7ff209221488>
>>> print(emp_2)
<__main__.Employee instance at 0x7ff2092214d0>
NOTE:- Both will be employee object and they both will be unique.
Both will be at different location in the memory.
------------------------
Using INSTANCE Variable:-
------------------------
class Employee:
pass
#Creating Instances of Employee class:-
emp_1 = Employee()
emp_2 = Employee()
#INSTANCE VARIABLE
emp_1.first = 'rudra'
emp_1.last = 'singh'
emp_1.email = 'rudra.singh@gmail.com'
emp_1.pay = 10000
#INSTANCE VARIABLE
emp_2.first = 'seema'
emp_2.last = 'singh'
emp_2.email = 'seema.singh@gmail.com'
emp_2.pay = 20000
print(emp_1.email)
print(emp_2.email)
------------
Using Class:-
------------
NOTE:- Class Variable are variable which are shared among Instances with in the class.
Class variable will be same for each variable.
class Employee:
def __init__(self, first, last, pay):
self.fname = first
self.lname = last
self.pay = pay
self.email = first + '.' + last + '@gmail.com'
#Creating Instances of Employee class:-
emp_1 = Employee('rudra','singh',10000)
emp_2 = Employee('seema','singh',20000)
>>> print(emp_1.email)
rudra.@gmail.com
>>> print(emp_2.email)
seema.@gmail.com
>>> print(emp_1.fname)
rudra
>>> print(emp_2.fname)
seema
# Other Way to print first and last name
print('{} {}'.format(emp_1.first, emp_2.last))
------------------------
NOTE:- Better to create a METHOD for FULL NAME as we are doing this only for a single employee.
------------------------
class Employee:
def __init__(self, first, last, pay):
self.fname = first
self.lname = last
self.pay = pay
self.email = first + '.' + '@gmail.com'
##METHOD for FULL NAME
def fullname(self):
return '{} {}'.format(self.fname, self.lname)
#Instance
emp_1 = Employee('rudra','singh',10000)
emp_2 = Employee('seema','singh',20000)
print(emp_2.fullname())
------------------
Calling or Running these method using class name:-
------------------
print(Employee.fullname(emp_1));
#similer to calling it using Instance
#emp_2.fullname()
-------------Class Variable Examples------------
class Employee:
def __init__(self, first, last, pay):
self.fname = first
self.lname = last
self.pay = pay
self.email = first + '.' + '@gmail.com'
#METHOD for FULL NAME
def fullname(self):
return '{} {}'.format(self.first, self.last)
#Method for Raise
def apply_raise(self):
self.pay = int(self.pay * 1.04)
#Instance
emp_1 = Employee('rudra','singh',10000)
emp_2 = Employee('seema','singh',20000)
print(emp1.pay) --> Will give present pay
emp_1.apply_raise()
print(emp.pay) --> Will print pay with raise.
------------
class Employee:
raise_amount = 1.04 #class Variable
def __init__(self, first, last, pay):
self.fname = first
self.lname = last
self.pay = pay
self.email = first + '.' + '@gmail.com'
##METHOD for FULL NAME
def fullname(self):
return '{} {}'.format(self.first, self.last)
#Method for Raise
def apply_raise(self):
self.pay = int(self.pay * Employee.raise_amount)
#We need to access class variable either using class--> Employee.raise_amount
#or using INSTANCE --> self.raise_amount
#Instance
emp_1 = Employee('rudra','singh',10000)
emp_2 = Employee('seema','singh',20000)
print(emp1.pay)
emp_1.apply_raise() #will raise only for emp1
print(emp1.pay)
NOTE:- Why we are using class vaiable using instance!! -->
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
All will give you the value of raise i.e. 1.04
NOTE:-
If we want to access an attribute using instance, it will check whether that instance contain attribute or not ! if not then it will check in the class from where it inharits , contains attrebute or not.
So as above instance emp_1 doesn't have attrebute but emp_1 inherits class Employee which contain the attrebute.
----------------------
Changing raise_amount:-
----------------------
Now If we want to change raise amount
Using Class:-
Employee.raise_amount = 1.05 #We also can do this by class method is examples given down the line
This will change raise_amount every where.
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
Result:-
1.05
1.05
1.05
------------------------------------
Let's change it only for instance:-
------------------------------------
emp_1.raise_amount = 1.05
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
Result:-
1.04
1.05
1.04
---------------------------------------------
Regular Methods , CLASS METHODS and STATIC METHODS
---------------------------------------------
class Employee:
raise_amount = 1.04 #class Variable
def __init__(self, first, last, pay): #---- Regular Method
self.fname = first
self.lname = last
self.pay = pay
self.email = first + '.' + '@gmail.com'
##METHOD for FULL NAME #---- Regular Method
def fullname(self):
return '{} {}'.format(self.first, self.last)
#Method for Raise
def apply_raise(self): #---- Regular Method
self.pay = int(self.pay * Employee.raise_amount)
# We need to access class variable either using class
# Employee.raise_amount or using INSTANCE --> self.raise_amount
#As below , in regular methods we use (self) but in class methods , we pass a variable i.e. (cls) in below example.
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amount = amount
#Instance
emp_1 = Employee('rudra','singh',10000)
emp_2 = Employee('seema','singh',20000)
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
#All will give you the value of raise i.e.
1.04
1.04
1.04
------
Now if we want to change it to 5 % then --> USE CLASS METHOD
Employee.set_raise_amt(1.05)
#Now All will give you the value of raise i.e.
1.05
1.05
1.05
NOTE :- Because set_raise_amt is a class method so it is changing all values.
Works same as Employee.raise_amount = 1.05 works.
----------------------------------------------------------------------------
Getting employee in string and after parsing getting the result using CLASS.
----------------------------------------------------------------------------
class Employee:
num_of_emps = 0
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
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amt = amount
Employee.set_raise_amt(1.05)
emp_str_1 = 'John-Doe-70000' #Getting employees as string
emp_str_2 = 'Steve-Smith-30000' #Getting employees as string
emp_str_3 = 'Jane-Doe-90000' #Getting employees as string
first, last, pay = emp_str_1.split('-') #Splitting string
new_emp_1 = Employee(first, last, pay) #Creating employee using class based on above split string.
print(new_emp_1.email) #Printing new_emp_1
print(new_emp_1.pay) #Printing new_emp_1
Result:-
John.Doe@email.com
70000
-----------------------------------------------------------------------------------------
In above we need to parse every time , So better to create class for that as given below.
Meaning Using Class method as alternative Constructor.
-----------------------------------------------------------------------------------------
class Employee:
num_of_emps = 0
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
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amt = amount
@classmethod #New Method for parsing
def from_string(cls, emp_str):
first, last, pay = emp_str.split('-')
return cls(first, last, pay)
emp_str_1 = 'John-Doe-70000'
emp_str_2 = 'Steve-Smith-30000'
emp_str_3 = 'Jane-Doe-90000'
new_emp_1 = Employee.from_string(emp_str_1)
print(new_emp_1.email)
print(new_emp_1.pay)
Result:-
John.Doe@email.com
70000
-----------------------------------------------------------------------------------
Regular Method:- Passed instances as first arguement, we call it self.
Class Method:- Automatically pass the class as cls in example, as a first arguement.
Static Method:- Don't Pass anything automatically. Don't pass instance or class.
-----------------------------------------------------------------------------------
Eg:-
We want a function that will take in a date and return :-
------------------
STATIC METHOD For above:-
------------------
class Employee:
num_of_emps = 0
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
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amt = amount
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split('-')
return cls(first, last, pay)
@staticmethod #STATIC METHOD
def is_workday(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
import datetime
my_date = datetime.date(2016, 7, 11)
print(Employee.is_workday(my_date))
Result:-
#Will return
False
#if saturday or sunday.
---------------------------------------------------------
Python OOP Tutorial 4: Inheritance - Creating Subclasses
---------------------------------------------------------
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)
class Developer(Employee): --Subclass #Inheritance - of class Employee in subclass Developer.
pass
dev_1 = Developer('Corey', 'Schafer', 50000) #Using Subclass
dev_2 = Developer('Test', 'Employee', 60000) ##Using Subclass
print(dev_1.email)
print(dev_2.email)
Output:-
Corey.schafer@gmail.com
Test.Employee@gmail.com
------
NOTE:- Because Developer class is Inherit class , so first code will look into Developer class for execution but it is empty , so it will go to Employee class because Developer class inharits from Employee class and will give output accordingly.
------
print(dev_1.pay)
dev_1.apply_raise()
print(dev_1.pay)
Output:-
50000
52000
----------------------------------
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)
class Developer(Employee): #class Developer inherits from Employee.
raise_amt = 1.10
def __init__(self, first, last, pay, prog_lang):
super().__init__(first, last, pay) #Use first, last, pay from Employee Class.
#Employee.__init__(self,first,last,pay) --- Other Way to do. Useful while doing multiple inharits.
self.prog_lang = prog_lang #Additional parameter prog_lang, we need to define here.
dev_1 = Developer('Corey', 'Schafer', 50000, 'Python')
dev_2 = Developer('Test', 'Employee', 60000, 'Java')
print(dev_1.email)
print(dev_1.prog_lang)
Output:-
Corey.schafer@gmail.com
Python
-----------------------
NOTE:-
super Keyword can be used to gain access to inherited methods – from a parent or sibling class –
that has been overwritten in a class object.
-----------------------
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)
class Developer(Employee):
raise_amt = 1.10
def __init__(self, first, last, pay, prog_lang):
super().__init__(first, last, pay)
self.prog_lang = prog_lang
class Manager(Employee):
def __init__(self, first, last, pay, employees=None):
super().__init__(first, last, pay)
if employees is None:
self.employees = []
else:
self.employees = employees
def add_emp(self, emp):
if emp not in self.employees:
self.employees.append(emp)
def remove_emp(self, emp):
if emp in self.employees:
self.employees.remove(emp)
def print_emps(self):
for emp in self.employees:
print('-->', emp.fullname())
dev_1 = Developer('Corey', 'Schafer', 50000, 'Python')
dev_2 = Developer('Test', 'Employee', 60000, 'Java')
mgr_1 = Manager('Sue', 'Smith', 90000, [dev_1])
print(mgr_1.email)
mgr_1.add_emp(dev_2)
mgr_1.remove_emp(dev_1)
mgr_1.print_emps()
--------------------------------------------------__repr__ and __str__-----------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------