Skip to content

Instantly share code, notes, and snippets.

@ausaki
Last active August 17, 2018 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ausaki/46ec0fec6a5d3684437380a9b21e5b13 to your computer and use it in GitHub Desktop.
Save ausaki/46ec0fec6a5d3684437380a9b21e5b13 to your computer and use it in GitHub Desktop.
metaclass_test.py
class MyMetaClass(type):
def __init__(cls, name, bases, attrs):
"""
initial class after __new__
"""
print '__init__ in the metaclass'
print 'cls:', cls
print 'name:', name
print 'bases:', bases
print 'attrs:', attrs
r = super(MyMetaClass, cls).__init__(name, bases, attrs)
print r # r is None
print '__init__ end\n'
return r
def __new__(meta_cls, name, bases, attrs):
"""
create a new class when define class with 'class statement'
"""
print '__new__ in the metaclass'
print 'cls:', meta_cls
print 'name:', name
print 'bases:', bases
print 'attrs:', attrs
r = super(MyMetaClass, meta_cls).__new__(meta_cls, name, bases, attrs)
print 'created class:', r
print '__new__ end\n'
return r
def __call__(cls, *args, **kwargs):
"""
create a new instance when call MyClass()
"""
print '__call__ in the metaclass'
print 'cls:', cls
print 'args:', args
print 'kwargs:', kwargs
try:
return cls.__instance
except AttributeError:
cls.__instance = super(MyMetaClass, cls).__call__(*args, **kwargs)
print 'created instance:', cls.__instance
print '__call__ end \n'
return cls.__instance
class Test(object):
__metaclass__ = MyMetaClass
def __new__(cls, *args, **kwargs):
print '__new__ in the Test'
print 'cls:', cls
print 'args:', args
print 'kwargs:', kwargs
ins = super(Test, cls).__new__(cls, *args, **kwargs)
print 'created instance:', ins
print '__new__ end\n'
return ins
def __init__(self, *args, **kwargs):
print '__init__ in the Test'
print 'self:', self
print 'args:', args
print 'kwargs:', kwargs
print '__init__ end \n'
t1 = Test(1, 2, 3)
t2= Test(3, 4, 5)
print 't1 is t2: ', t1 is t2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment