如何让Python类的__init__仅在未调用其他方法时执行?
实现你要的行为的几种方案
首先得明确:在Python中,只要你通过ThisClass()创建实例,一定会触发__init__方法——这是Python类实例化的固有逻辑。所以你原来的写法ThisClass().otherFunc()必然会先执行__init__打印"hello",再执行otherFunc打印"yeet"。要实现你要的效果,我们需要换一种思路绕过这个限制,下面是几个可行的方案:
方案1:把otherFunc改成类方法
类方法不需要实例化就能调用,这样你可以直接通过类调用它,完全跳过实例化和__init__的执行。同时保留直接实例化触发__init__的行为:
class ThisClass(): def __init__(self): print("hello") @classmethod def otherFunc(cls): print("yeet") # 直接实例化,输出hello ThisClass() # 调用类方法,输出yeet(不会触发__init__) ThisClass.otherFunc()
这是最符合Python风格的实现方式,唯一的区别是调用方法时不用先创建实例,如果你能接受这个调用形式,这个方案是最优解。
方案2:用自定义实例逻辑适配原调用写法
如果你一定要保留ThisClass().otherFunc()的调用形式,我们可以通过__new__和装饰器配合,控制__init__是否执行:
from functools import wraps def skip_init(func): @wraps(func) def wrapper(self, *args, **kwargs): # 给实例打标记,告诉__init__不需要执行 self._skip_init = True return func(self, *args, **kwargs) return wrapper class ThisClass(): def __new__(cls, *args, **kwargs): instance = super().__new__(cls) # 默认标记为需要执行__init__ instance._skip_init = False return instance def __init__(self): if not getattr(self, '_skip_init', False): print("hello") @skip_init def otherFunc(self): print("yeet") # 直接实例化,输出hello ThisClass() # 调用方法,输出yeet(__init__被跳过) ThisClass().otherFunc()
这个方案的核心是:创建实例时先通过__new__设置标记,调用目标方法时修改标记,让__init__根据标记决定是否执行逻辑。完美匹配你提出的两种调用场景。
方案3:用工厂函数控制实例创建
另一种思路是把实例创建的逻辑抽离到工厂函数中,根据需求决定是否执行初始化:
class ThisClass(): def __init__(self): print("hello") def otherFunc(self): print("yeet") def create_this_class(call_method=False): # 创建实例但不执行__init__ instance = object.__new__(ThisClass) if call_method: instance.otherFunc() return instance else: instance.__init__() return instance # 直接创建实例,输出hello create_this_class() # 创建实例并调用方法,输出yeet create_this_class(call_method=True)
这个方案更灵活,适合后续需要扩展更多初始化逻辑的场景,但需要改变原有的调用方式。
内容的提问来源于stack exchange,提问作者Harrison Sills
相关产品推荐
相关产品推荐

