【问题标题】:Using __delitem__ with a class object rather than an instance in Python将 __delitem__ 与类对象而不是 Python 中的实例一起使用
【发布时间】:2013-11-27 16:27:33
【问题描述】:

我希望能够将__delitem__ 与类级变量一起使用。 我的用例可以在here 找到(使用_reg_funcs 的答案),但它基本上涉及一个装饰器类,其中包含一个它已装饰的所有函数的列表。有没有办法让类对象支持__delitem__?我知道我可以专门为此目的保留一个实例,但我宁愿不必这样做。

class Foo(object):
    _instances = {}

    def __init__(self, my_str):
        n = len(self._instances) + 1
        self._instances[my_str] = n
        print "Now up to {} instances".format(n)

    @classmethod
    def __delitem__(cls, my_str):
        del cls._instances[my_str]


abcd = Foo('abcd')
defg = Foo('defg')

print "Deleting via instance..."
del abcd['abcd']
print "Done!\n"

print "Deleting via class object..."
del Foo['defg']
print "You'll never get here because of a TypeError: 'type' object does not support item deletion"

【问题讨论】:

    标签: python class instance class-method


    【解决方案1】:

    当您编写del obj[key] 时,Python 调用obj 类的__delitem__ 方法,而不是obj。所以del obj[key] 的结果是type(obj).__delitem__(obj, key)。

    在你的情况下,这意味着type(Foo).__delitem__(Foo, 'abcd')。 type(Foo) 是 type,而 type.__delitem__ 未定义。您无法修改 type 本身,您需要将 Foo 本身的类型更改为可以修改的内容。

    你可以通过定义一个新的元类来做到这一点,它只是type的一个子类,然后指示Python使用你的新元类来创建Foo类(不是@987654335的实例@,但 Foo 本身)。

    class ClassMapping(type):
        def __new__(cls, name, bases, dct):
            t = type.__new__(cls, name, bases, dct)
            t._instances = {}
            return t
        def __delitem__(cls, my_str):
            del cls._instances[my_str]
    
    class Foo(object):
        __metaclass__ = ClassMapping
        def __init__(self, my_str):
            n = len(Foo._instances) + 1
            Foo._instances[my_str] = n
            print "Now up to {} instances".format(n)
    

    将Foo 的元类从type 更改为ClassMapping 为Foo 提供

    1. 引用字典的类变量_instances
    2. 一个从_instances 中删除参数的__delitem__ 方法。

    【讨论】:

    • 工作,谢谢。但令我惊讶的是“当你编写 del obj[key] 时,Python 调用了 obj 类的 delitem 方法,而不是 obj 的方法”。这是为什么呢?
    • 与任何方法一样,函数与类绑定,而不是对象,对象是函数的隐式第一个参数。尝试将__delitem__ 设为类方法而不是常规实例方法将是 Python 根本无法实现的特殊情况。
    猜你喜欢
    • 2013-04-01
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2023-02-16
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    相关资源
    最近更新 更多