在Python中使用类对象而不是实例

2024-05-01 13:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够将__delitem__与类级变量一起使用。 我的用例可以在here(使用_reg_funcs的答案)中找到,但它基本上涉及一个decorator类,该类保存了它所修饰的所有函数的列表。有没有办法让类对象支持__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"

Tags: instancesselfhereobjectfoomydefclass
1条回答
网友
1楼 · 发布于 2024-05-01 13:26:21

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

在你的例子中,这意味着type(Foo).__delitem__(Foo, 'abcd')type(Foo)type,而type.__delitem__未定义。您不能修改type本身,您需要将Foo本身的类型更改为可以修改的类型。

为此,可以定义一个新的元类,它只是type的一个子类,然后指示Python使用新的元类创建Foo类(不是Foo的实例,而是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__方法。

相关问题 更多 >