<分区>
我想做这样的事情......
def helloWorld():
print "Hello world!"
str.helloWorld = helloWorld
"foo".helloWorld()
这会打印出“Hello world!”
编辑:请参阅 Can I add custom methods/attributes to built-in Python types?
<分区>
我想做这样的事情......
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/