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!"
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,解决您的问题.
总之,你不能.Python方法将继承String并从那里开始工作.
这是一个想法。它并不完美,因为它不适用于所有字符串,但它可能会有所帮助。
设置字符串或任何其他对象的属性:
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)
| 归档时间: |
|
| 查看次数: |
7703 次 |
| 最近记录: |