如何为现有内置Python类型(如字符串)添加自定义属性?

16 投票
8 回答
16091 浏览
提问于 2025-04-15 20:26

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

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

这样就会打印出“Hello world!”

编辑:可以参考 我可以给内置的Python类型添加自定义方法/属性吗?

8 个回答

5

这里有个想法。虽然这个方法并不完美,因为它并不适用于所有字符串,但可能会对你有帮助。

要设置一个字符串或其他对象的属性,可以这样做:

def attr(e,n,v): #will work for any object you feed it, but only that object
    class tmp(type(e)):
        def attr(self,n,v):
            setattr(self,n,v)
            return self
    return tmp(e).attr(n,v)

下面是一个例子:

>>> def helloWorld():
...     print("hello world!") #python 3
...
>>> a=attr("foo",'heloWorld',helloWorld)
>>> a
'foo'
>>> a.helloWorld()
hello world!
>>> "foo".helloWorld()
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    "foo".helloWorld()
AttributeError: 'str' object has no attribute 'helloWorld'
24

在CPython中,你可以使用ctypes来访问解释器的C接口,这样你就可以在运行时修改内置类型。

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()

虽然这看起来很有趣,可能也很值得研究…… 千万不要在实际的代码中使用它。最好是继承内置类型,或者试着找找有没有其他更符合Python风格的方法来解决你的问题。

11

简单来说,你是做不到的。用Python的方式是创建一个字符串的子类,然后从那里开始处理。

撰写回答