我应该担心__init_subclass__开始的方式吗?

我在项目中使用init_subclass,当我在代码首次在解释器中运行时遇到内置方法时,我有点犹豫,而没有通过实例化包含类或子类直接引用列举。


有人可以告诉我发生了什么事,并向我指出其安全使用的任何示例吗?


class Timer():


    def __init__(self):

        pass


    def __init_subclass__(cls):

        print('Runner.', cls)

        print('Timer Dictionary :', Timer.__dict__.keys())

        # print(Timer.__init_subclass__()) # Forbidden fruit...

        pass


class Event(Timer):

    print("I'll take my own bathroom selfies...thanks anyway.")


    def __init__(self):

        print('This is nice, meeting on a real date.')


if __name__ == '__main__': # a good place for a breakpoint

        date = Event()

        date

编辑 - - - - - - - - - - - - - - - - - - - - - - - - - --


根据收到的解释,将原始代码重新构建为有用的东西。


class Timer():


    subclasses = {}


    def __init__(self):

        pass


    def __init_subclass__(cls, **kwargs):

        print('Runner.', cls)

        print('Timer Dictionary :', Timer.__dict__.keys())

        # print(Timer.__init_subclass__()) # Forbidden fruit...

        super().__init_subclass__(**kwargs)

        cls.subclasses[cls] = []



class Event(Timer):

    print("I'll take my own bathroom selfies...thanks anyway.")


    def __init__(self):

        print('This is nice, meeting on a real date.')

        if self.__class__ in super().subclasses:

            # get the index and link the two

            super().subclasses[self.__class__].append(self)


if __name__ == '__main__': # a good place for a breakpoint

    date = Event()

    date

    duty = Event()

    duty

    print(Timer.subclasses)


开心每一天1111
浏览 178回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python