What is a clean, pythonic way to have multiple constructors in Python?

后端 未结 13 2119
醉梦人生
醉梦人生 2020-11-22 07:12

I can\'t find a definitive answer for this. As far as I know, you can\'t have multiple __init__ functions in a Python class. So how do I solve this problem?

13条回答
  •  鱼传尺愫
    2020-11-22 07:14

    This is pretty clean way i guess and tricky

    class A(object):
        def __init__(self,e,f,g):
    
            self.__dict__.update({k: v for k,v in locals().items() if k!='self'})
        def bc(self):
            print(self.f)
    
    
    k=A(e=5,f=6,g=12)
    k.bc() # >>>6
    

提交回复
热议问题