سؤال

Consider the following class in Python 3:

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

Is there a keyword (similar to Python's super in this case) that can be used to access class variables in place of putting the class name Foo?

هل كانت مفيدة؟

المحلول

type(self) or self.__class__ will return the actual class of self, which might be a subclass of Foo or Foo:

class Foo(AnotherClass):
    id_counter = 0
    def __init__(self):
        super().__init__()
        self.id = type(self).id_counter
        type(self).id_counter += 1
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top