相关疑难解决方法(0)

python内置类型的扩展方法!

是否可以为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

42
推荐指数
3
解决办法
2万
查看次数

在Python中设置只读属性?

考虑到Python的动态性,如果不可能的话,我会感到震惊:

我想改变执行情况sys.stdout.write.

我从这个答案得到了我的另一个问题的想法:https://stackoverflow.com/a/24492990/901641

我试着写这个:

original_stdoutWrite = sys.stdout.write

def new_stdoutWrite(*a, **kw):
    original_stdoutWrite("The new one was called! ")
    original_stdoutWrite(*a, **kw)

sys.stdout.write = new_stdoutWrite
Run Code Online (Sandbox Code Playgroud)

但它告诉我AttributeError: 'file' object attribute 'write' is read-only.

这是一个很好的尝试,让我不要做一些潜在的(可能)愚蠢的事情,但我真的很想继续这样做.我怀疑解释器有一些我可以修改的查找表,但我在Google上找不到类似的东西.__setattr__也没用 - 它返回了关于属性为只读的完全相同的错误.

我特意寻找Python 2.7解决方案,如果这很重要,虽然没有理由拒绝投入适用于其他版本的答案,因为我怀疑未来的其他人会在这里看到与其他版本类似的问题.

python stdout readonly-attribute python-2.7

14
推荐指数
1
解决办法
9053
查看次数

标签 统计

python ×2

python-2.7 ×1

readonly-attribute ×1

stdout ×1