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

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

    Use classmethod decorator for your Load method:

    class B(object):    
        def __init__(self, name, data):
            self._Name = name
            #store data
    
        @classmethod
        def Load(cls, file, newName):
            f = open(file, "rb")
            s = pickle.load(f)
            f.close()
    
            return cls(newName, s)
    

    So you can do:

    loaded_obj = B.Load('filename.txt', 'foo')
    

    Edit:

    Anyway, if you still want to omit __init__ method, try __new__:

    >>> class A(object):
    ...     def __init__(self):
    ...             print '__init__'
    ...
    >>> A()
    __init__
    <__main__.A object at 0x800f1f710>
    >>> a = A.__new__(A)
    >>> a
    <__main__.A object at 0x800f1fd50>
    

提交回复
热议问题