How to create a class instance without calling initializer?

后端 未结 4 940
-上瘾入骨i
-上瘾入骨i 2020-12-08 19:31

Is there any way to avoid calling __init__ on a class while initializing it, such as from a class method?

I am trying to create a case and punctuation i

4条回答
  •  一生所求
    2020-12-08 20:10

    A trick the standard pickle and copy modules use is to create an empty class, instantiate the object using that, and then assign that instance's __class__ to the "real" class. e.g.

    >>> class MyClass(object):
    ...     init = False
    ...     def __init__(self):
    ...         print 'init called!'
    ...         self.init = True
    ...     def hello(self):
    ...         print 'hello world!'
    ... 
    >>> class Empty(object):
    ...     pass
    ... 
    >>> a = MyClass()
    init called!
    >>> a.hello()
    hello world!
    >>> print a.init
    True
    >>> b = Empty()
    >>> b.__class__ = MyClass
    >>> b.hello()
    hello world!
    >>> print b.init
    False
    

    But note, this approach is very rarely necessary. Bypassing the __init__ can have some unexpected side effects, especially if you're not familiar with the original class, so make sure you know what you're doing.

提交回复
热议问题