我在項目中使用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... passclass 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)
添加回答
舉報
0/150
提交
取消