- 在调用 super 之后 python 可以自动执行__init__代码吗

我有类似的东西:


class SuperClass(object):


 def __init__(self):


 # initialization stuff



 def always_do_this_last(self):


 # cleanup stuff



class SubClass(SuperClass):


 def __init__(self):


 super().__init__()


 # intermediate stuff


 self.always_do_this_last()



是否可以自动调用最后一行? SuperClass的每个子类都需要执行清理。

时间:

你有 2个选项:

使用不同的方法作为初始值设定项,然后调用 always_do_this_last


class SuperClass(object):


 def __init__(self):


 self._init() # initialize


 self.always_do_this_last() # clean up



 def _init(self):


 pass # initialization stuff



 def always_do_this_last(self):


 pass # cleanup stuff



class SubClass(SuperClass):


 def _init(self):


 super()._init()


 # intermediate stuff



使用元类


class CleanupMeta(type):


 def __call__(cls, *args, **kwargs):


 obj = super().__call__(*args, **kwargs)


 obj.always_do_this_last()


 return obj



class SuperClass(metaclass=CleanupMeta):


 def __init__(self):


 pass # initialization stuff



 def always_do_this_last(self):


 pass # cleanup stuff



class SubClass(SuperClass):


 def __init__(self):


 super().__init__()


 # intermediate stuff



...