自古以来我们制造东西的方法都是“自上而下”的,是用切削、分割、组合的方法来制造。然而,生命是自下而上地,自发地建造起来的,这个过程极为低廉。 ——王晋康 《水星播种》
print type(1) # <type 'int'>
print type(int) # <type 'type'> class MyClass(object): pass print type(MyClass) # <type 'type'> print type(type) # <type 'type'>
class Integer(int):
name = 'my integer'
def increase(self, num):
return num + 1
# -------------------
Integer = type('Integer', (int, ), {
'name': 'my integer',
'increase': lambda self, num: \
num + 1 # 很酷的写法,不是么
})
class Integer(int): __metaclass__ = IntMeta
Integer = IntMeta('Integer', (int, ), {})
sensitive_words_list = ['asshole', 'fuck', 'shit']
def detect_sensitive_words(string):
'''检测敏感词汇'''
words_detected = filter(lambda word: word in string.lower(), sensitive_words_list)
if words_detected:
raise NameError('Sensitive words {0} detected in the string "{1}".' \
.format(
', '.join(map(lambda s: '"%s"' % s, words_detected)),
string
)
)
class CleanerMeta(type):
def __new__(cls, class_name, bases, attrs):
detect_sensitive_words(class_name) # 检查类名
map(detect_sensitive_words, attrs.iterkeys()) # 检查属性名
print "Well done! You are a polite coder!" # 如无异常,输出祝贺消息
return super(CleanerMeta, cls).__new__(cls, class_name, bases, attrs)
# 重要!这行一定不能漏!!这回调用内建的类构造器来构造类,否则定义好的类将会变成 None
现在,只需这样定义基类:
class APIBase(object):
__metaclass__ = CleanerMeta
# ...
那么所有 APIBase 的派生类都会接受安全审查(奸笑~~):
class ImAGoodBoy(APIBase):
a_polite_attribute = 1
# [Output] Well done! You are a polite coder!
class FuckMyBoss(APIBase):
pass
# [Output] NameError: Sensitive words "fuck" detected in the string "FuckMyBoss".
class PretendToBePolite(APIBase):
def __fuck_your_asshole(self):
pass
# [Output] NameError: Sensitive words "asshole", "fuck" detected in the string "_PretendToBePolite__fuck_your_asshole".
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有