Is there a way to instantiate a class without calling __init__?

前端 未结 6 1175
故里飘歌
故里飘歌 2020-11-28 05:04

Is there a way to circumvent the constructor __init__ of a class in python?

Example:

class A(object):    
    def __init__(self):
               


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 05:53

    Taking your question literally I would use meta classes :

    class MetaSkipInit(type):
        def __call__(cls):
            return cls.__new__(cls)
    
    
    class B(object):
        __metaclass__ = MetaSkipInit
    
        def __init__(self):
            print "FAILURE"
    
        def Print(self):
            print "YEHAA"
    
    
    b = B()
    b.Print()
    

    This can be useful e.g. for copying constructors without polluting the parameter list. But to do this properly would be more work and care than my proposed hack.

提交回复
热议问题