我有一个类,有时候我想要“重置”它。我认为通过调用init方法来重构它会比手动清空类中所有变量及其使用的模块更好。我的担忧是,我不确定这是否是一个良好的设计模式,或者GC是否正确地清除了旧对象。
以下是一个示例:
from modules import SmallClass
from modules import AnotherClass
class BigClass(object):
def __init__(self, server=None):
"""construct the big class"""
self.server = server
self.small_class = SmallClass(self.server)
self.another_class = AnotherClass(small_class)
def reset_class(self):
"""reset the big class"""
self.__init__(self.server)
这会在后续造成问题吗?还是有更好的方法处理?
__init__
也应该调用super()
的 init。 - Ambersuper()
不一定会返回直接父类,如果其他东西具有多重继承。例如,如果C
子类化了A
和B
,它们各自子类化对象,则C
的 MRO 可能是C-A-B-object
,在这种情况下,在 A 的__init__
中调用super()
将返回B
,即使A
仅是object
的子类。经验法则是,如果您要覆盖 init,则始终调用super()
的 init。 - AmberAttribute 'small_class' defined outside __init__ (attribute-defined-outside-init)
。在__init__
中是否最好有self.small_class = None
,并在reset
中实例化它? - Jono