Created
July 11, 2017 08:54
-
-
Save zhusimaji/31fe157b62703923bf6177f05f0fdbac to your computer and use it in GitHub Desktop.
v2ex
This file contains 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
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