#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:Runcheng
class_name = "Spam"
base = ()
def run(self):
print("%s is runing" % self.name)
class_dict = {
"name":"zou",
"run":run
}
S = type("Spam", base, class_dict)
print(S)
print(type(S))
s = S()
print(type(s))
s.run()
# 利用type产生元类
SB = type("SB", (object,), {})
s = SB()
s.name = "zou"
print(type(s)) # <class '__main_ _.SB'>
print(s.__dict__) # {'name': 'zou'}
# 3 自定义元类限制注释信息
from collections import Iterable,Iterator
class Mymeta(type):
def __init__(self, class_name, base=None, dict=None ):
print(self)
print(class_name)
print(base)
print(dict)
for key in dict:
if not callable(dict[key]):continue
if not dict[key].__doc__:
raise Exception("你还没写注释信息")
def __call__(self, *args, **kwargs):
print("from mytype",self,args,kwargs) # from mytype <class '__main__.Foo'> ('zou',) {}
obj = self.__new__(self)
self.__init__(obj, *args, **kwargs)
return obj
class Foo(metaclass=Mymeta):
x = 1
def __init__(self,name):
"注释信息" # 不写这里的注释,直接抛出元类的异常信息
self.name = name
def run(self):
"run function"
print("running")
f = Foo("zou") # from mytype <class '__main__.Foo'> ('zou',) {}
print(Foo.__dict__)
网友评论