How to create a class instance without calling initializer?

后端 未结 4 942
-上瘾入骨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:20

    When feasible, letting __init__ get called (and make the call innocuous by suitable arguments) is preferable. However, should that require too much of a contortion, you do have an alternative, as long as you avoid the disastrous choice of using old-style classes (there is no good reason to use old-style classes in new code, and several good reasons not to)...:

       class String(object):
          ...
    
       bare_s = String.__new__(String)
    

    This idiom is generally used in classmethods which are meant to work as "alternative constructors", so you'll usually see it used in ways such as...:

    @classmethod 
    def makeit(cls):
        self = cls.__new__(cls)
        # etc etc, then
        return self
    

    (this way the classmethod will properly be inherited and generate subclass instances when called on a subclass rather than on the base class).

提交回复
热议问题