扩展类(特别是添加新方法,而不是更改现有方法)的另一种方法,甚至是内置类,是使用一个预处理器,该预处理器增加了扩展到Python本身范围之外/之上的能力,在Python真正看到扩展之前将其转换为普通的Python语法。
例如,我这样做是为了扩展Python 2的str()类。str()是一个特别有趣的目标,因为它与引用的数据(如'this'和'that')存在隐式关联。
下面是一些扩展代码,其中唯一添加的非Python语法是extend:testDottedQuad位:extend:testDottedQuad
def testDottedQuad(strObject):
if not isinstance(strObject, basestring): return False
listStrings = strObject.split('.')
if len(listStrings) != 4: return False
for strNum in listStrings:
try: val = int(strNum)
except: return False
if val < 0: return False
if val > 255: return False
return True
之后,我可以编写输入到预处理器的代码:if '192.168.1.100'.testDottedQuad():
doSomething()
dq = '216.126.621.5'
if not dq.testDottedQuad():
throwWarning();
dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
print 'well, that was fun'
预处理器会吃掉它,在不使用monkeypatching的情况下吐出普通的Python,Python会按照我希望的那样做。
正如c预处理器向c添加功能一样,Python预处理器也可以向Python添加功能。
我的预处理器实现对于堆栈溢出答案来说太大了,但是对于那些可能感兴趣的人来说,它是GitHub上的here。