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

前端 未结 6 1169
故里飘歌
故里飘歌 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:57

    Not really. The purpose of __init__ is to instantiate an object, and by default it really doesn't do anything. If the __init__ method is not doing what you want, and it's not your own code to change, you can choose to switch it out though. For example, taking your class A, we could do the following to avoid calling that __init__ method:

    def emptyinit(self):
        pass
    A.__init__ = emptyinit
    a = A()
    a.Print()
    

    This will dynamically switch out which __init__ method from the class, replacing it with an empty call. Note that this is probably NOT a good thing to do, as it does not call the super class's __init__ method.

    You could also subclass it to create your own class that does everything the same, except overriding the __init__ method to do what you want it to (perhaps nothing).

    Perhaps, however, you simply wish to call the method from the class without instantiating an object. If that is the case, you should look into the @classmethod and @staticmethod decorators. They allow for just that type of behavior.

    In your code you have put the @staticmethod decorator, which does not take a self argument. Perhaps what may be better for the purpose would a @classmethod, which might look more like this:

    @classmethod
    def Load(cls, file, newName):
        # Get the data
        data = getdata()
        # Create an instance of B with the data
        return cls.B(newName, data)
    

    UPDATE: Rosh's Excellent answer pointed out that you CAN avoid calling __init__ by implementing __new__, which I was actually unaware of (although it makes perfect sense). Thanks Rosh!

提交回复
热议问题