【问题标题】:How to write a static python getitem method?如何编写静态python getitem方法?
【发布时间】:2011-09-05 11:41:01
【问题描述】:

我需要进行哪些更改才能完成这项工作?

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

print A[0]

请注意,我在 A 类型上调用 __getitem__ 方法。

【问题讨论】:

    标签: python static operator-keyword magic-methods


    【解决方案1】:

    当一个对象被索引时,特殊方法__getitem__首先在对象的类中查找。一个类本身就是一个对象,一个类的类通常是type。所以要为一个类覆盖__getitem__,你可以重新定义它的元类(使它成为type的子类):

    class MetaA(type):
        def __getitem__(cls,val):
            return "It works"
    
    class A(object):
        __metaclass__=MetaA
        pass
    
    print(A[0])
    # It works
    

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

    class A(object, metaclass=MetaA):
        pass
    

    【讨论】:

    • @ups:元类在 Python3 中以不同的方式指定。我已经添加了代码来展示上面的方法。
    【解决方案2】:

    Python 3.7 引入了__class_getitem__

    class A:
        def __class_getitem__(cls, key):
            return "It works"
    
    print(A[0])
    

    【讨论】:

      猜你喜欢
      • 2015-02-21
      • 2018-05-23
      • 1970-01-01
      • 2012-12-06
      • 2019-08-31
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      相关资源
      最近更新 更多