如何编写静态python getitem方法? [英] How to write a static python getitem method?
本文介绍了如何编写静态python getitem方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
要进行这项工作,我需要更改什么?
What do I need to change to make this work?
class A:
@staticmethod
def __getitem__(val):
return "It works"
print A[0]
请注意,我正在以A
类型调用__getitem__
方法.
Note that I am calling the __getitem__
method on the type A
.
推荐答案
为对象建立索引时,将首先在对象的类中查找特殊方法__getitem__
.一个类本身就是一个对象,一个类的类通常是type
.因此,要为类覆盖__getitem__
,您可以重新定义其元类(使其成为type
的子类):
When an object is indexed, the special method __getitem__
is looked for first in the object's class. A class itself is an object, and the class of a class is usually type
. So to override __getitem__
for a class, you can redefine its metaclass (to make it a subclass of type
):
class MetaA(type):
def __getitem__(cls,val):
return "It works"
class A(object):
__metaclass__=MetaA
pass
print(A[0])
# It works
在Python3中,元类是通过以下方式指定的:
In Python3 the metaclass is specified this way:
class A(object, metaclass=MetaA):
pass
这篇关于如何编写静态python getitem方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文