I want to do something like this...
def helloWorld():
print "Hello world!"
str.helloWorld = helloWorld
"foo".helloWorld()
Which would print out "Hello world!"
EDIT: Refer to Can I add custom methods/attributes to built-in Python types?
Adding attributes to a Python class is very straight forward, you just use the '. ' operator after an instance of the class with whatever arbitrary name you want the attribute to be called, followed by its value.
On CPython you can use ctypes to access the C-API of the interpreter, this way you can change builtin types at runtime.
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()
Although this is interesting to look at and may be quite interesting to figure out... don't ever use it in productive code. Just subclass the builtin type or try to figure out if there is another, may be more pythonic, approach to your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With