您不能直接将方法添加到原始类型。但是,您可以对类型进行子类化,然后将其替换为内置/全局名称空间,从而实现所需的大多数效果。不幸的是,通过文字语法创建的对象将继续为原始类型,并且不会具有新的方法/属性。
这是它的样子
# Built-in namespace
import __builtin__
# Extended subclass
class mystr(str):
def first_last(self):
if self:
return self[0] + self[-1]
else:
return ''
# Substitute the original str with the subclass on the built-in namespace
__builtin__.str = mystr
print str(1234).first_last()
print str(0).first_last()
print str('').first_last()
print '0'.first_last()
output = """
14
00
Traceback (most recent call last):
File "strp.py", line 16, in <module>
print '0'.first_last()
AttributeError: 'str' object has no attribute 'first_last'
"""