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