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

jed*_*mao 11 python string polymorphism attributes

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

def helloWorld():
  print "Hello world!"
str.helloWorld = helloWorld
"foo".helloWorld()
Run Code Online (Sandbox Code Playgroud)

哪个会打印出"Hello world!"

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

Das*_*Ich 21

在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()
Run Code Online (Sandbox Code Playgroud)

虽然这很有意思,但可能非常有趣,因为... 不要在生产代码中使用它.只是继承内置类型或尝试弄清楚是否有另一个,可能更pythonic,解决您的问题.

  • [forbiddenfruit](https://github.com/clarete/forbiddenfruit)允许在几个Python版本上修补内置对象. (2认同)

scz*_*zzo 8

总之,你不能.Python方法将继承String并从那里开始工作.

  • 子类化内置函数很少有用.创建对它们进行操作的函数几乎总是更好,或者在添加某些状态的情况下,使用内置为属性的实例创建类. (4认同)
  • 子类化dict以实现OrderedDict,MultiDict,ImmutableDict或它们的组合是非常常见的.另一方面,dict是一个集合str不是. (3认同)

Sce*_*sto 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)
Run Code Online (Sandbox Code Playgroud)

这是一个例子:

>>> 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'
Run Code Online (Sandbox Code Playgroud)