python - 如何将自己的自定义属性添加到现有的内置 Python 类型?像一根绳子?

标签 python string attributes polymorphism

<分区>

我想做这样的事情......

def helloWorld():
  print "Hello world!"
str.helloWorld = helloWorld
"foo".helloWorld()

这会打印出“Hello world!”

编辑:请参阅 Can I add custom methods/attributes to built-in Python types?

最佳答案

在 CPython 上,您可以使用 ctypes 访问解释器的 C-API,这样您就可以在运行时更改内置类型。

import ctypes as c


class PyObject_HEAD(c.Structure):
    _fields_ = [
        ('HEAD', c.c_ubyte * (object.__basicsize__ -
                              c.sizeof(c.c_void_p))),
        ('ob_type', c.c_void_p)
    ]

_get_dict = c.pythonapi._PyObject_GetDictPtr
_get_dict.restype = c.POINTER(c.py_object)
_get_dict.argtypes = [c.py_object]

def get_dict(object):
    return _get_dict(object).contents.value

def my_method(self):
    print 'tada'
get_dict(str)['my_method'] = my_method

print ''.my_method()

虽然这看起来很有趣,而且可能很有趣……不要在生产代码中使用它。只需将内置类型子类化或尝试找出是否有另一种可能更像 pythonic 的方法来解决您的问题。

关于python - 如何将自己的自定义属性添加到现有的内置 Python 类型?像一根绳子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2444680/

相关文章:

python - 我可以遍历数据 block 笔记本中的小部件吗?

python - 检查域名是否注册

python - Python 文档字符串中的字符串操作

python - 将属性分配给类方法

coding-style - 使用属性以 Python 方式限制属性访问

python - 如何从另一个模块更改类对象参数(python)

python - Jupyterhub 错误 503 : Proxy Target Missing

python - Tkinter 条目和网格

java - 字符串内容和 user_input 不允许我输入多个单词

java - 迭代java中的字符串集