Skip to main content
 首页 » 编程设计

python之在python中是否可以编写一个在子类的__init__之后自动调用的方法

2025年05月04日9jackei

我正在编写一个供其他人使用的库。

对于每个重要的功能,我都有一个基类。用户应该对这些进行子类化,并添加他们的重要方法版本。

现在我想我需要添加一个“setup()”函数,它必须在子类的init() 之后运行,但是Problem 已经有不同的子类了。在那里,我不想让人碰那些东西。

我也在 2.7 上开发。

说:

class Problem: 
    def __init__(self,**kwargs): 
        #this and that 
 
    def setup(self,**kwargs): 
        #Generic stuff that needs to be done after SpecificProblem.__init__() is called. 
 
class SpecificProblem(Problem): 
    def __init__(self,**kwargs): 
        Problem.__init__(self,**kwargs) 
        #this and that 

请您参考如下方法:

与其让子类覆盖 __init__,不如让他们编写一个名为 make 的方法。如:

class Problem: 
    def __init__(self,**kwargs): 
        self.make(**kwargs) 
        self.setup(**kwargs) 
 
    def setup(self,**kwargs): 
        #Generic stuff that needs to be done after SpecificProblem.__init__() is called. 
 
    def make(self,**kwargs): 
        # method to be overwritten by subclasses 
        pass 
 
class SpecificProblem(Problem): 
    def make(self,**kwargs): 
        #this and that 

解决这个问题有不同的方法。如果您希望编写 SpecificProblem 的人负责完成的所有事情以及何时完成,那么元类方法将是有意义的。但是,如果您想适本地“分离关注点”,那么我的方法可以让您做到这一点。