我希望能够将__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"
编写
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
本身)。将
Foo
的元类从type
更改为ClassMapping
提供了Foo
_instances
_instances
中删除参数的__delitem__
方法。相关问题 更多 >
编程相关推荐