4

たとえば、これは可能ですか?

class Foo(object):
    class Meta:
        pass

class Bar(Foo):
    def __init__(self):
        # remove the Meta class here?
        super(Bar, self).__init__()
4

2 に答える 2

4

継承された基本クラスからクラス属性を削除することはできません。同じ名前のインスタンス変数を設定することで、それらをマスクすることしかできません。

class Bar(Foo):
    def __init__(self):
        self.Meta = None  # Set a new instance variable with the same name
        super(Bar, self).__init__()

もちろん、独自のクラスでクラス変数をオーバーライドすることもできます。

class Bar(Foo):
    Meta = None

    def __init__(self):
        # Meta is None for *all* instances of Bar.
        super(Bar, self).__init__()
于 2012-09-07T09:34:45.720 に答える
1

クラスレベルでそれを行うことができます:

class Bar(Foo):
    Meta = None

(またsuper、コンストラクターの呼び出しは冗長です)

于 2012-09-07T09:36:33.377 に答える