Last active
June 5, 2017 05:13
-
-
Save dboyliao/3855e3e8111363a02bd5c2dce8095bdb to your computer and use it in GitHub Desktop.
Python __new__, __init__ and __del__ example script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from __future__ import print_function | |
class Foo(object): | |
def __new__(cls, *args, **kwargs): | |
print("Foo.__new__ invoked") | |
print("args:", args) | |
print("kwargs:", kwargs) | |
# in python3, you can just simply call super() here | |
super_obj = super(Foo, cls) | |
if super_obj.__new__ is object.__new__: | |
# reach the end of class mro (object) | |
self = super_obj.__new__(cls) | |
else: | |
self = super_obj.__new__(cls, *args, **kwargs) | |
# the use of super() here seems to be irrelevent, | |
# but super() really comes to handy when we're dealing | |
# with inheritance | |
return self | |
def __init__(self, *args, **kwargs): | |
# Note that __init__ must share the same API as __new__ | |
# since all the arguments for __new__ will be passed to __init__ | |
# according to the python website (https://docs.python.org/3.6/reference/datamodel.html#object.__new__) | |
print("Foo.__init__ invoked") | |
self.args = args | |
for k, v in kwargs.items(): | |
setattr(self, k, v) | |
def __del__(self): | |
print("Foo.__del__") | |
super_obj = super(Foo, self) | |
try: | |
super_obj.__del__() | |
except: | |
# object do not have __del__ method | |
pass | |
class Bar(Foo): | |
def __del__(self): | |
print("Bar.__del__") | |
super_obj = super(Bar, self) | |
super_obj.__del__() | |
if __name__ == "__main__": | |
b = Bar(1, 2, a=3, b=2) | |
b = 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment