How to create a class instance without calling initializer?

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

    Pass another argument to the constructor, like so:

    def __init__(self, string, simple = None):
        if simple is None:
            self.__string = tuple(string.split())
            self.__simple = tuple(self.__simple())
        else:
            self.__string = string
            self.__simple = simple
    

    You can then call it like this:

    def __getitem__(self, key):
        assert isinstance(key, slice)
        return String(self.__string[key], self.__simple[key])
    

    Also, I'm not sure it's allowed to name both the field and the method __simple. If only for readability, you should change that.

提交回复
热议问题