1

set.union作为属性分配给一个类时,并从该类的实例变量调用此属性将引发错误:TypeError: descriptor 'union' for 'set' objects doesn't apply to 'Foo' object. 这里有一个例子来说明这个问题:

class Foo:
    bar = set.union

set.union({1}, {2})
# {1, 2}
Foo.bar({1}, {2})
# {1, 2}
Foo().bar({1}, {2})
# Traceback (most recent call last):
#   File "<input>", line 1, in <module>
# TypeError: descriptor 'union' for 'set' objects doesn't apply to 'Foo' object

set.union分配为实例属性时不会发生这种情况:

class Foobar:
    def __init__(self):
        self.bar = set.union

Foobar().bar({1}, {2})
# {1, 2}

是什么导致了这个错误?为什么这只发生在类属性上?

4

0 回答 0