Skip to content

Instantly share code, notes, and snippets.

@zhusimaji
Created July 11, 2017 08:54
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 zhusimaji/31fe157b62703923bf6177f05f0fdbac to your computer and use it in GitHub Desktop.
Save zhusimaji/31fe157b62703923bf6177f05f0fdbac to your computer and use it in GitHub Desktop.
v2ex
class MyType(type):
def __init__(cls, what, bases=None, dict=None):
print 'call myType.__init__()'
print "class name:"+what
print "class bases:"+str(bases)
print "class attributions:"+str(dict)
super(MyType,cls).__init__(what, bases, dict)
def __new__(cls, name, bases, attrs):
print "call MyType.__new__()"
return type.__new__(cls, name, bases, attrs)
class Foo(object):
__metaclass__ = MyType #1
def __init__(self, name=None):
self.name = name
print "Foo.__init__ self=", self
print "Foo self.name=", self.name
def __new__(cls, *args, **kwargs):
print "Foo.__new__ cls=", cls
return(object.__new__(cls, *args, **kwargs))
def __call__(self, cls):
print "Foo.__call__ cls=", cls
print "Foo.__call__ self=", self
def func(self):
print 'function is there'
if __name__ == '__main__':
print "---------test1---------" #3
obj2=Foo() #4
输出
all MyType.__new__()
call myType.__init__()
class name:Foo
class bases:(<type 'object'>,)
class attributions:{'__module__': '__main__', '__metaclass__': <class '__main__.MyType'>, '__new__': <function __new__ at 0x1081ed3
98>, 'func': <function func at 0x1081ed488>, '__call__': <function __call__ at 0x1081ed410>, '__init__': <function __init__ at 0x10
81ed320>}
---------test1---------
Foo.__new__ cls= <class '__main__.Foo'>
Foo.__init__ self= <__main__.Foo object at 0x108187250>
Foo self.name= None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment