Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何编写静态python getitem方法?_Python_Static_Operator Keyword_Magic Methods - Fatal编程技术网

如何编写静态python getitem方法?

如何编写静态python getitem方法?,python,static,operator-keyword,magic-methods,Python,Static,Operator Keyword,Magic Methods,我需要做什么改变才能让这一切顺利进行 class A: @staticmethod def __getitem__(val): return "It works" print A[0] 请注意,我正在调用类型A上的\uuuuu getitem\uuuuu方法对对象进行索引时,将首先在对象的类中查找特殊方法\uu getitem\uuuu。类本身是一个对象,类的类通常是类型。因此,要覆盖类的\uuu getitem\uuu,可以重新定义其元类(使其成为类型的子类

我需要做什么改变才能让这一切顺利进行

class A:
    @staticmethod
    def __getitem__(val):
        return "It works"

print A[0]

请注意,我正在调用类型
A

上的
\uuuuu getitem\uuuuu
方法对对象进行索引时,将首先在对象的类中查找特殊方法
\uu getitem\uuuu
。类本身是一个对象,类的类通常是
类型
。因此,要覆盖类的
\uuu getitem\uuu
,可以重新定义其元类(使其成为
类型的子类)


在Python3中,元类是这样指定的:

class A(object, metaclass=MetaA):
    pass
介绍了Python 3.7

A类:
定义类获取项(cls,键):
返回“它工作”
打印(A[0])

@ups:元类在Python3中以不同的方式指定。我在上面添加了代码来演示如何操作。
class A(object, metaclass=MetaA):
    pass