TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial…

Follow publication

Python Data Model

All about Pythonic Class: The Life Cycle®

Farhad Naeem
TDS Archive
Published in
8 min readNov 1, 2020
Image: source

4. What actually happens when we define a class

class Footballer():
game = "Football"

def __init__(self, name, club):
self.name = name
self.club = club

def a_method(self):
return None

print(Footballer.__dict__)

# Output
'''
{'__module__': '__main__', 'game': 'Football', '__init__': <function Footballer.__init__ at 0x7f10c4563f28>, 'a_method': <function Footballer.a_method at 0x7f10c45777b8>, '__dict__': <attribute '__dict__' of 'Footballer' objects>, '__weakref__': <attribute '__weakref__' of 'Footballer' objects>, '__doc__': None}
'''
def outer_init(self, name, club):
self.name = name
self.club = club

Footballer1 = type("Footballer1", (), {"game":"Soccer", "__init__": outer_init, "b_method": lambda self: None})
print(Footballer1.__dict__)
print(Footballer1.game)

# Output
'''
{'game': 'Soccer', '__init__': <function outer_init at 0x7f10c4510488>, 'b_method': <function <lambda> at 0x7f10c4510f28>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Footballer1' objects>, '__weakref__': <attribute '__weakref__' of 'Footballer1' objects>, '__doc__': None}
Soccer
'''
class Bar():
def __init__(self, obVar):
self.obVar = obVar

>>> obj = Bar("a string") ----------------[1]
# putting object parameter into a temporary variable
>>> tmpVar = Bar.__new__(Bar, "another string")
>>> type(tmpVar)
>>> __main__.Bar
>>> tmpVar.obVar -------------------------[2]# the class is not initialised yet
# It will throw errors
>>> AttributeError Traceback (most recent call last)
....
AttributeError: 'Bar' object has no attribute 'obVar'
------------------------------------------------------
# initialise a temporary variable
>>> tmpVar.__init__("a string") ---------------[3]
>>> tmpVar.obVar
>>> 'another string'
>>> obVar = tmpVar
>>> obVar.obVar
>>> 'another string'

5. Life Cycle of a Class

import requests

# Another name space
var = "a class variable."

def __init__(self, url):
self.__response = requests.get(url)
self.code = self.__response.status_code

def server_info(self):
for key, val in self.__response.headers.items():
print(key, val)

def __del__(self): ---------------------- [1]
self.__response.close()
print("[!] closing connection done...")
# Injecting meta from another namespace
Response = type('Response', (), {"classVar":var,"__init__": __init__, "server":server_info, "__del__":__del__})

# Let's connect to our home server on my father's desk
resp = Response("http://192.168.0.19")
print(type(Response))
print(resp.code)
resp.server()
del resp # It will call the DE-CONSTRUCTOR# Output
'''
<class 'type'>
401
Date Fri, 25 Sep 2020 06:13:50 GMT
Server Apache/2.4.38 (Raspbian)
WWW-Authenticate Basic realm="Restricted Content"
Content-Length 461Keep-Alive timeout=5, max=100
Connection Keep-Alive
Content-Type text/html; charset=iso-8859-1
[!] closing connection done... # resp object destroyed
'''

6. Garbage Collection

import sys

class Bar():
pass

print(sys.getrefcount(Bar)) # default reference count is 5

a = Bar()
b = Bar()
c = Bar()

print(sys.getrefcount(Bar)) # reference count increased by 3


del a , b , c

print(sys.getrefcount(Bar)) # reference count decreased by 3

# Output
'''
5
8
5

'''
class Foo():
pass

obj.var = obj

Final Thoughts:

References:

TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Farhad Naeem
Farhad Naeem

Written by Farhad Naeem

Enjoying simple thoughts in a simple world

Responses (1)

Write a response