重新定义Python内置数据类型 [英] Redefining Pythons builtin datatypes
问题描述
是否可以重新定义方括号[]使用的对象?
Is it possible to redefine which object the brackets [] use?
我可以对list
对象进行子类化,但是如何使解释器使用我的子类来代替内置列表对象?是否有可能?
I can subclass the list
object, but how to I make the interpreter use my subclass in place of the buildin list object? Is it possible?
(我很确定我对问题使用了错误的术语-随时可以编辑)
(I'm pretty sure I'm using the wrong terms for the question- feel free to edit)
>>> class mlist(list):
... def __init__(self):
... list.__init__(self)
... def __getitem__(self, item):
... return list.__getitem__(self, item) * 2
...
>>> testlist = mlist()
>>> testlist.append(21)
>>> testlist[0]
42
>>> list = mlist() # maybe setting the 'list' type will do it?
>>> testlist = []
>>> testlist.append(21)
>>> testlist[0]
21 # Nope
>>>
我对此没有实际用途-只是好奇.
I don't have a practical use for this- just curious.
推荐答案
在运行发布的代码后尝试运行代码
Try running the code after you've run the code you posted
>>> testlist = list()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'mlist' object is not callable
现在,使用我发布的代码确定类型
Now, determine the type using the code I've posted
>>> type([])
<type 'list'>
>>> type(list)
<class '__main__.mlist'>
>>> type(testlist)
<type 'list'>
似乎[]
创建了list
,而不是mlist
,它看起来很奇怪:S
it seems that []
creates list
, instead of mlist
, it looks strange :S
更新
我检查了使用dis
生成的字节码,并生成了以下代码
I checked the bytecode generated using dis
, and the code below was generated
>>> import dis # python's disassembler
>>> def code1():
... return []
...
>>> dis.dis(code1)
2 0 BUILD_LIST 0
3 RETURN_VALUE
>>> def code2():
... return list()
...
>>> dis.dis(code2)
2 0 LOAD_GLOBAL 0 (list)
3 CALL_FUNCTION 0
6 RETURN_VALUE
似乎list
将调用分配给它的任何内容,而[]
将被转换为BUILD_LIST
字节码.看来[]
并没有转换为list
,因此[]
的行为被卡在了创建列表上.
It appears that list
will invoke whatever is assigned to it, while []
will be converted to BUILD_LIST
bytecode. It appears that []
is not translated to list
, hence []
's behavior is stucked to creating list.
更新2
Python类可以更新
Python class can be updated
>>> class NewList(list):
... pass
...
>>> a = NewList()
>>> a.append(23)
>>> a[0]
23
>>> def double_getitem(self, key):
... return list.__getitem__(self, key) * 2
...
>>> NewList.__getitem__ = double_getitem
>>> a[0]
46
好吧,除了内置类(如列表)
Well, except for builtin classes, like list
>>> list.__getitem__ = double_getitem
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'list'
这篇关于重新定义Python内置数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!