您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

我可以将自定义方法/属性添加到内置Python类型吗?

我可以将自定义方法/属性添加到内置Python类型吗?

您不能直接将方法添加到原始类型。但是,您可以对类型进行子类化,然后将其替换为内置/全局名称空间,从而实现所需的大多数效果。不幸的是,通过文字语法创建的对象将继续为原始类型,并且不会具有新的方法/属性

这是它的样子

# 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'
"""
python 2022/1/1 18:39:02 有252人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶