Python访问类变量的关键词

2024-04-20 04:55:17 发布

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

考虑Python3中的以下类:

class Foo(AnotherClass):
    id_counter = 0
    def __init__(self):
        super().__init__()
        self.id = Foo.id_counter
        Foo.id_counter += 1

是否有一个关键字(在本例中类似于Python的super)可以用来访问类变量而不是放置类名Foo?你知道吗


Tags: selfidfooinitdefcounter关键字python3
1条回答
网友
1楼 · 发布于 2024-04-20 04:55:17

type(self)self.__class__将返回self的实际类,该类可能是FooFoo的子类:

class Foo(AnotherClass):
    id_counter = 0
    def __init__(self):
        super().__init__()
        self.id = type(self).id_counter
        type(self).id_counter += 1

相关问题 更多 >