from warnings import warn
#元类需要继承type类
class ReqStrSugRepr(type):
def __init__(cls, name, bases, attrd):
#构造函数需要传递的参数为类名,基类,类属性字典
super(ReqStrSugRepr, cls).__init__(name, bases, attrd)
# 判断__str__字符串是否在类的属性字典里
if '__str__' not in attrd:
raise TypeError('Class requires overriding of __str__()')
if '__repr__' not in attrd:
warn('Class suggests overriding of __repr__()\n', stacklevel=3)
class Foo(object):
#给类指定元类
__metaclass__ = ReqStrSugRepr
def foo(self):
pass
#这一段代码不用创建类来测试,直接运行一下就会报错,可见元类的功力。
# <type 'int'>
# <type 'str'>
type(1)
type('mink')
X = type('X', (object,), dict(a=1))
# 等于
class X(object):
a = 1
def say(self):
print 'hello'
X = type('X', (object,), dict(say=say))
x = X()
# pirnt hello
x.say()
class PrivateMetaclass(type):
def __new__(cls, name, parents, attrs):
attrs = dict(('__%s' % k, v) for k, v in attrs.itmes())
return super(PrivateMetaclass, cls).__new__(cls, name, parents, attrs)
class A(object):
__metaclass__ = PrivateMetaclass
a = 1
b = 2
a = A()
# raise AttributeError
print a.a, a.b
# print 1, 2
print a.__a, a.__b
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有