我可以覆盖 Python 列表显示吗?
我想更改 Python 列表显示的行为,以便它们不生成 list
,而是生成我编写的 list
的子类。 (注意:我认为这不是一个好主意;我这样做是为了好玩,而不是实际使用。)
这就是我所做的:
old_list = list
class CallableList(old_list):
def __init__(self, *args):
old_list.__init__(self)
for arg in args:
self.append(arg)
def __call__(self, start, end=None):
if end:
return self[start:end]
return self[start]
list = CallableList
完成后,这将返回列表的第三个元素:
x = list(1, 2, 3)
print x(2)
但这仍然是给出一个错误:
x = [1, 2, 3]
print x(2)
该错误非常简单:
Traceback (most recent call last):
File "list_test.py", line 23, in <module>
print x(2)
TypeError: 'list' object is not callable
我认为可能没有办法做到这一点,但我找不到任何明确说明的内容。有什么想法吗?
I'd like to change the behavior of Python's list displays so that instead of producing a list
, they produce a subclass of list
that I've written. (Note: I don't think this is a good idea; I'm doing it for fun, not actual use.)
Here's what I've done:
old_list = list
class CallableList(old_list):
def __init__(self, *args):
old_list.__init__(self)
for arg in args:
self.append(arg)
def __call__(self, start, end=None):
if end:
return self[start:end]
return self[start]
list = CallableList
Once that's done, this returns the third element of the list:
x = list(1, 2, 3)
print x(2)
but this still gives an error:
x = [1, 2, 3]
print x(2)
The error is pretty straightforward:
Traceback (most recent call last):
File "list_test.py", line 23, in <module>
print x(2)
TypeError: 'list' object is not callable
I think there's probably no way of doing this, but I can't find anything that says so definitively. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能简单地覆盖用于内置类型的语法糖,因为这发生在编译器级别。始终显式调用构造函数。
You cannot trivially override the syntactic sugar used for built-in types, since this happens at the compiler level. Always call the constructor explicitly.
您无法从 Python 内部更改它。诸如列表推导之类的构造始终使用内置列表类型,而不是您在当前命名空间中定义的单词
list
的任何类型。如果要更改内置类型,则必须编辑Python源代码并重新编译。假设您使用的是 CPython 实现,它位于 对象/listobject.c。You can't change it from within Python. Constructs such as list-comprehensions always use the built-in list type, not whatever you've defined the word
list
to in the current namespace. If you want to change the built-in type, you have to edit the Python source code and recompile. Assuming you're using the CPython implementation, it lives in Objects/listobject.c.因此,您并没有真正重新定义类型“list”,您只是更改了名称空间,以便类型列表的 list() 方法现在与您的 CallableList 类型发生冲突。为了避免这种情况,
so you haven't really redefined type 'list,' you've only changed your namespace so that the type list's list() method now clashes with your type CallableList type. To avoid this,