Skip to content

Commit f122693

Browse files
committed
Updated previous notes, and added notes for Garbage Collection
1 parent 16f8c5d commit f122693

File tree

2 files changed

+164
-5
lines changed

2 files changed

+164
-5
lines changed

10. Garbage Collection.py

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import gc
2+
import time
3+
import sys
4+
###gc module is responsible for garbage collector related methods
5+
class Garbage_Collection:
6+
''' An object is considered to be useless, when there is no ref., varibale pointing towards it. i.e., it is not possible to access that object. Garbage collection is useful to remove all these useless objects, if there are too much of these useless objects, and thery ar not destroyed, then it leads to memory constraitn issues, wihihcsops further creation of enw objects.
7+
In languages like C++, both object creation and garbage collection are manual i,e only the programemr, can create teh objcet, as well as destruct teh object when ther eis no eneed of it. But the programmers, mostly don't destuct the unsued or not needed objects, which leads to memory issesu in C++
8+
Whereas in langauges like Java, Python, we have automatic as well as manual garbage collection as well. So, when an useless object is dounf i.e where no ref., varibel ispoitnign otoawards teh object, the "garabge collector" will atuomatically dsestuecs teh objects, leads to no emmroy constraitn issues.
9+
In python, based on our requirement, we can either enable or disable the garbage collector, which is not possuble in Java, makes python special.
10+
How do u manually make an object, uselesss such that it will be destroeyd by the garbage collector.
11+
EIther deletet the reg., var., potingin to teh obejct, or point the ref. var to None
12+
Eg., s = Garbage_Collection()
13+
Either do,
14+
i) del s (OR)
15+
ii) s = None
16+
in first cae, we deleted teh variabel itself,ins eocnd cae, we just chagning tis potingin toawards.
17+
18+
Constructor - def __init__()
19+
Destructor - def __del__():
20+
Destructor is used, to perform any clean up proceesse in the obecjt, before it's destruction or for any resource re-allocation process for the object.
21+
22+
A garbage collector won;t immediately desturcts an object,when its find it useless. Before destructing any useless object, the garbage collector,will call teh destructor, destructor is repsonsible for ccleanup of the object, like databse connections , netwrok connections with teh object, and freeing up resources,that is consumed by the obejct, only afte executio of desturctor, garbage collector will delete the object.
23+
Daemon threads are the threads that runs on backgorudn all tiem.Garbage colelctior is an niec e.g, for daemon threads.
24+
Destructor __del__() in python is same asthte finalise keyword used in Java
25+
The PVM, is responsible for calling the Garbage collector. Then, then garbage collector is responsible for calling the destructor,it calls the destructor, for clean up purpeos,tehn finally the object is destroyed.
26+
The destructor is either expleicitely created by hte user, if the usre did not provide the destuctor explcieilty, like Java, in Python also, have teh OBJECT classs, as the parent of all classes,it ahs an default object destructor,which does nothing. Garbage colelctiro is responsibel for exeuttingthe destuctor atumatically. When explcitely destuctor is privide,it exeuted that, whern it si not provide,it used the parent OBJECT class's desturcrotro,which does not do anything. It;s the same for constructors also. IF wedidnt provide explciit constircutor, PVM wil uses the default constructor in the Parent OBject class, whcih does nothign.
27+
'''
28+
29+
def __init__(self):
30+
print("Im initiating....")
31+
32+
def __del__(self):
33+
print("The garbage collector, called thed destructor(me) to clean up the resources, so after i execute, teh garbage collector will destruct the object")
34+
35+
36+
print("Is garbage collection enabled?",gc.isenabled())
37+
print("Disable the garbage collector... ")
38+
gc.disable()
39+
print("Is garbage collection enabled?",gc.isenabled())
40+
print("Enable the garbage collector again...")
41+
gc.enable()
42+
print("Is garbage collection enabled?",gc.isenabled())
43+
44+
45+
46+
print("Case 1: ")
47+
t1 = Garbage_Collection()
48+
t1 = None
49+
time.sleep(3)
50+
print("I'm the last line of this program, after i printed, the program will get terminated")
51+
print("Here, removing the ref., var., of the object, will make the Garbage collector immediately call teh destructor and then destroys the object")
52+
53+
54+
print("Case 2: ")
55+
t1 = Garbage_Collection()
56+
time.sleep(3)
57+
print("I'm the last line of this program, after i printed, the program will now get terminated")
58+
print("Here, even if i didnt remove teh ref pointer, or didnt delete the ref., variable, when the program reaches at it's last, before termination, the Garbage collector will remove all the objects at last, before termnation of teh program, whetehr the object has the ref.,v ar., or not, doesnt matter")
59+
60+
61+
print("Case 3: ")
62+
gc.disable()
63+
t1 = Garbage_Collection()
64+
t1 = None
65+
time.sleep(3)
66+
print("I'm the last line of this program, after i printed, the program will now get terminated")
67+
print("Here, even after being disabling the garabge collector, still the object,whose ref., we marked as None here gets destructed, becuase , in theroy, gc.disable shoudl dsiable teh gabage collector. But in reality, the wroking of gabrage colelctor varies from paltofrm to paltofrm,so only the platofrm,w=inwhcih we wrok,willd ecied whether todisabelt eh gabage colelctor or not")
68+
69+
70+
print("Case 4: ")
71+
gc.disable()
72+
t1 = Garbage_Collection()
73+
time.sleep(3)
74+
print("I'm the last line of this program, after i printed, the program will now get terminated")
75+
print("Here, even after being disabling the garabge collector, still the object gets destructed, even we didnt delete teh ref., to it, becuase , in theroy, gc.disable shoudl dsiable teh gabage collector. But in reality, the wroking of gabrage colelctor varies from paltofrm to paltofrm,so only the platofrm,w=inwhcih we wrok,willd ecied whether todisabelt eh gabage colelctor or not")
76+
77+
78+
print("Case 5: ")
79+
t1 = Garbage_Collection()
80+
t2 = t1
81+
t3 = t2
82+
t4 = t3
83+
del t1
84+
time.sleep(1)
85+
print("Even after deleting t1, object is not destroyed yet, since, t2,t3,t4 are pointing towards the object")
86+
del t2
87+
time.sleep(1)
88+
print("Even after deleting t2, object is not destroyed yet, since, t3,t4 are pointing towards the object")
89+
del t3
90+
time.sleep(1)
91+
print("Even after deleting t3, object is not destroyed yet, since, t4 are pointing towards the object")
92+
del t4
93+
print("Now,i deleted all the ref., variables")
94+
time.sleep(1)
95+
print("Since, here one obejct has 4 ref., variabels,a ll 4 ref,. variables needs to be removed, to make the object useless, to mket he gc to take action")
96+
print("End of Application,I'm the last line")
97+
98+
99+
print("Case 6: ")
100+
li = [Garbage_Collection(),Garbage_Collection(),Garbage_Collection()]
101+
time.sleep(3)
102+
print("The li object is pointed to None now")
103+
li = None
104+
time.sleep(3)
105+
print("Since, here the li is ppitned towards None, all the objects inside li,will get destroyed one by one")
106+
print("Im the last line of execution, Apllication is completed")
107+
108+
109+
print("Find no of ref., variables to an object using sys module methods")
110+
t1 = Garbage_Collection()
111+
t2 = t1
112+
t3 = t2
113+
t4 = t3
114+
print("Here, including all the external 4 ref., pointers, exepclitely mentioned by the programmer, adn icnclduong the implicit self ref., variable provided by the PVM, totally we have ",sys.getrefcount(t1),"ref variables")

9. Inner_Classes.py renamed to 9. Inner_Classes, nested classes and nested methods.py

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ class SECE:
33
def __init__(self,funds,expenses):
44
self.total_funds = funds
55
self.total_expenses = expenses
6-
self.contact_details = self.contact_us()
7-
6+
self.current_director = "Shri.R.Rajaram"
7+
self.contact_details = self.contact_us(self.current_director)
8+
89

910
def financial_status(self):
1011
print(f"Funds availabe: {self.total_funds}, Expenses: {self.total_expenses}")
@@ -45,7 +46,7 @@ def add_courses(self, name):
4546
self.course_count+=1
4647

4748
class Courses_offered:
48-
''' This (Courses_offered) is an nested class here. Here,we can udnerstand teh improtnae of inner classes. i.e if we didnt use any inner classes, then in the outer class SECE itself, we will be forced to have all teh attributes like funds, expenses, dept name,s tudents, faculty count, course credits, code, faculty handled,whihc oworudlnto eb nice., Having inner classes, ameks it better. i.e for e.g, If we need to have a detasl about a person adn his DOB details, liek dd,mm,yyyy instaead of ahvinga ll teh person relted attribteus, as welll as the attibutes mm,dd,yy in teh consturctor of eprson class itslef, have all the eprson realted attirbtues, create inner class DOB , initlaise dd,mm,yyyy ihitn it,adn inteh otuer Person class, call teh DOB inner class, as a instance variable liek e.g, self.dob = self.DOB()'''
49+
''' This (Courses_offered) is an nested class here. Here,we can udnerstand teh improtnae of inner classes. i.e if we didnt use any inner classes, then in the outer class SECE itself, we will be forced to have all teh attributes like funds, expenses, dept name,s tudents, faculty count, course credits, code, faculty handled,whihc oworudlnto eb nice., Having inner classes, ameks it better. i.e for e.g, If we need to have a details about a person ,which also includes his DOB details as dd,mm,yyyy. We'll have the DOB as inner class, the reasons are - since DOB can't exist, if a person does not exist. The next reason is, DOB consists of 3 attributes dd,mm,yyyy. Instaead of having all these attributes along with other person related attribteus, in teh consturctor of Person outer class itslef, have all the Person realted attirbtues in the outer class as it is, create inner class DOB , initialise dd,mm,yyyy ihitn it,adn inteh otuer Person class, call teh DOB inner class, as a instance variable liek e.g, self.dob = self.DOB()'''
4950

5051
def __init__(self,course_code,credits,course_name, outer_instance):
5152
self.course_code = course_code
@@ -57,19 +58,59 @@ def __init__(self,course_code,credits,course_name, outer_instance):
5758
def update_course_details(self):
5859
print("Here, we access the outer class., method by creating a instance varibale,which points the ref., variable of the outer Class")
5960
self.access_dept.add_courses(self.course_name)
60-
61+
62+
63+
class ControllerOfExaminations:
64+
''' Here, we use nested method insdie a emthod, nested methods,are used ins cenarios,where a specific funcitoanilty within the funciton in needed, repeatabieltiy,so taht if we write tehm out as a nested emthdo,we can reuse them as mcuh we want, instead of writing thema gian and agian, another use case, is when u need to isolate a speerate funciroanlity or logic inside teh funciton, deu to the fact, which is, somehwat nort genralyl used,or any sepfici -use case or funcitaonilty basde, do not want to mix up with the main logic
65+
Note: There is no nested methods in Java, there are nested methods only in Python'''
66+
@staticmethod
67+
def pass_or_fail_calculator():
68+
def validate_marks(cia_1, cia_2,cia_3,external,assignments,presentation,quiz):
69+
if cia_1<50 and cia_2<50 and cia_3<50:
70+
print("Sorry, u failed,all internal exams, you are not permitted to write the external exams.")
71+
return
72+
73+
if external<50:
74+
print("Sorry, u failed, in external exam, you didn't pass the exam.")
75+
return
76+
77+
cia_1 = cia_1*0.08
78+
cia_2 = cia_2*0.08
79+
cia_3 = cia_3*0.08
80+
81+
internal_marks = assignments+presentation+cia_1+cia_2+cia_3+quiz
82+
if internal_marks<20:
83+
print("Sorry u do not have the necessary internal marks")
84+
return
85+
86+
total_marks = internal_marks+external
87+
if total_marks>50:
88+
print("Congrats! You passed the exam")
89+
else:
90+
print("Sorry, u failed the exam")
91+
92+
validate_marks(80,60,90,80,5,5,6)
93+
validate_marks(10,50,30,60,4,3,5)
94+
validate_marks(90,60,50,70,4,5,6)
95+
96+
97+
98+
99+
61100

62101

63102

64103
class contact_us:
65104
''' To call me, from the outer class SECE, they have created an instance of mine (contact us) and used the instance variable (contact_details) to call me, and execute my methods'''
66-
def __init__(self):
105+
def __init__(self, director_name):
106+
self.curr_director = director_name
67107
self.phone_no = "+91 4259200300"
68108
self.e_mail = "sece@sece.ac.in"
69109
self.location = " Kondampatti [Post], Vadasithur (via), Coimbatore – 641 202, Tamil Nadu, India"
70110

71111
def display(self):
72112
print("##### Contact Us #####")
113+
print("Director Name: ",self.curr_director)
73114
print("Phone: ",self.phone_no)
74115
print("e_mail: ",self.e_mail)
75116
print("Location: ",self.location)
@@ -119,6 +160,10 @@ def sanction_loan(client,loan_amt):
119160
big_data_analytics_course.update_course_details()
120161
print(f"After: AI_DS Courses: {ai_ds.courses}, Count: {ai_ds.course_count}")
121162

163+
pass_or_fail = SECE.ControllerOfExaminations()
164+
165+
print(pass_or_fail.__doc__)
166+
pass_or_fail.pass_or_fail_calculator()
122167

123168

124169

0 commit comments

Comments
 (0)