#!/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__)
python元类示例
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- class Test(object): age = 20 def __init__(self, name)...
- 原文出处:https://www.cnblogs.com/tkqasn/p/6524879.html