是否可以为python内置类型添加扩展方法?我知道我可以通过简单地添加新方法来将扩展方法添加到已定义的类型.如下:
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
Run Code Online (Sandbox Code Playgroud)
但是有没有办法将扩展方法添加到python built'in类型,如list,dict,...
list.myExtension = lambda self,x:x * 2
list.myExtension(10)
Run Code Online (Sandbox Code Playgroud) 我希望有人可以回答这个对Python有深刻理解的:)
请考虑以下代码:
>>> class A(object):
... pass
...
>>> def __repr__(self):
... return "A"
...
>>> from types import MethodType
>>> a = A()
>>> a
<__main__.A object at 0x00AC6990>
>>> repr(a)
'<__main__.A object at 0x00AC6990>'
>>> setattr(a, "__repr__", MethodType(__repr__, a, a.__class__))
>>> a
<__main__.A object at 0x00AC6990>
>>> repr(a)
'<__main__.A object at 0x00AC6990>'
>>>
Run Code Online (Sandbox Code Playgroud)
注意repr(a)如何不产生"A"的预期结果?我想知道为什么会这样,如果有办法实现这个目标......
我对比一下,下面的例子可行(也许是因为我们没有尝试覆盖特殊方法?):
>>> class A(object):
... def foo(self):
... return "foo"
...
>>> def bar(self):
... return "bar"
...
>>> from types import …Run Code Online (Sandbox Code Playgroud) 的__dict__一种类型是一个dictproxy被只读对象.我想知道它的目的是什么.它仅适用于"不允许修改内置类型"吗?我发现了一种可以绕过它的方法.我知道修改内置类型并不是一个好主意.但我试图cdef class在飞行中修改Cython.
我想知道是否有任何危险的修改__dict__的cdef class这种方式?
这是代码:
import gc
gc.get_referents(float.__dict__)[0]["square"] = lambda self: self*self
(3.14).square()
Run Code Online (Sandbox Code Playgroud) 我正在寻找一种方法将异常的可打印输出更改为愚蠢的消息,以便了解有关 python 内部结构的更多信息(并与朋友搞混;),但到目前为止还没有成功。
考虑以下代码
try:
x # is not defined
except NameError as exc:
print(exc)
Run Code Online (Sandbox Code Playgroud)
代码应输出 name 'x' is not defined
我希望将输出更改为the name 'x' you suggested is not yet defined, my lord. Improve your coding skills.
到目前为止,我明白你不能改变,__builtins__因为它们被“烘焙”为 C 代码,除非:
我已经尝试了两种解决方案,但没有成功:
禁果解决方案:
from forbiddenfruit import curse
curse(BaseException, 'repr', lambda self: print("Test message for repr"))
curse(BaseException, 'str', lambda self: print("Test message for str"))
try:
x
except NameError as exc:
print(exc.str()) # Works, shows test …Run Code Online (Sandbox Code Playgroud) 我知道,这是错的,但有可能吗?我认为当一个对象.__iter__返回一个迭代器时,它被认为是一个可迭代的对象?那么为什么这不起作用呢?
>>> from forbiddenfruit import curse
>>> def __iter__(self):
... for i in range(self):
... yield i
>>> curse(int, "__iter__", __iter__)
>>> for x in 5:
... print x
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
Run Code Online (Sandbox Code Playgroud)
int 也似乎有一个__iter__现在的方法:
>>> int(5).__iter__
<bound method int.__iter__ of 5>
Run Code Online (Sandbox Code Playgroud)