Skip to content

Instantly share code, notes, and snippets.

@kaka19ace
Created November 3, 2015 16:35
Show Gist options
  • Save kaka19ace/65a8e69e7ec18e578f1f to your computer and use it in GitHub Desktop.
Save kaka19ace/65a8e69e7ec18e578f1f to your computer and use it in GitHub Desktop.
test_metaclass
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @file test_metaclass.py
# @author kaka_ace <[email protected]>
# @date Nov 03 2015
# @brief
#
class MyMeta(type):
def __new__(cls, name, bases, d):
print("-------------- meta new --------------")
print(cls)
print(name)
print(bases)
print(d)
cls = type.__new__(cls, name, bases, d)
return cls
def __init__(cls, name, bases, d):
print("-------------- meta init --------------")
print(cls)
print(name)
print(bases)
print(d)
super(MyMeta, cls).__init__(name, bases, d)
def __call__(cls, *args, **kwargs):
print("-------------- meta call --------------")
print(cls)
print(args)
print(kwargs)
return type.__call__(cls, *args, **kwargs)
class Base(metaclass=MyMeta):
STATUS = 1
def __new__(cls, *args, **kwargs):
print("-------------- Base new --------------")
print(cls)
print(args)
print(kwargs)
return super(Base, cls).__new__(cls) # object 不需要加参数啦
def __init__(self, *args, **kwargs):
print("-------------- Base init --------------")
print(self)
print(args)
print(kwargs)
super(Base, self).__init__()
# 此时输出:
# meta new Base
# meta init Base
class Derive(Base):
D_STATUS = 1
def __new__(cls, *args, **kwargs):
print("-------------- Derive new --------------")
print(cls)
print(args)
print(kwargs)
return super(Derive, cls).__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
print("-------------- Derive init --------------")
print(self)
print(args)
print(kwargs)
super(Derive, self).__init__(*args, **kwargs)
# 此时输出:
# meta new Derive
# meta init Derive
"""
b 实例生成过程:
meta call
Base new
b 实例生成
b init -> Base init
"""
b1 = Base(1)
"""
d 实例生成过程:
meta call
Derive new
Base new
b 实例生成
b init -> Derive init -> Base init
"""
d1 = Derive('a')
print("-----------------------------")
# 同 b1, d1
b2 = Base()
d2 = Derive()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment