可以将__init__用作初始化的常规方法,而不用作构造函数吗? [英] May __init__ be used as normal method for initialization, not as constructor?

查看:102
本文介绍了可以将__init__用作初始化的常规方法,而不用作构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时使用 __ init __ 作为已存在对象的初始化方法似乎是合理的,即:

Sometimes it looks reasonable to use __init__ as initialization method for already existing object, i.e.:

class A():
    def __init__(self, x):
        self.x = x

    def set_state_from_file(self, file):
        x = parse_file(file)
        self.__init__(x)

此实现我看到以下内容:

As alternative to this implementation I see the following:

class A():
    def __init__(self, x):
        self.init(x)        

    def init(self, x):
        self.x = x

    def set_state_from_file(self, file):
        x = parse_file(file)
        self.init(x)

我认为代码过于复杂。

It seems to me as over-complication of code. Is there any guideline on this situation?

推荐答案

__ init __ 不是吗?构造函数。这是一种初始化方法,在实例已经为您构造之后称为之后(实际的构造方法称为 __ new __() )。

__init__ is not a constructor. It is an initialisation method, called after the instance was already constructed for you (the actual constructor method is called __new__()).

如果您需要重新初始化,始终可以从代码中再次调用它,这不是样式冲突。实际上,它在Python标准库中使用。请参见 multiprocessing.heap。 Heap()实现例如:

You can always call it again from your code if you need to re-initialise, this isn't a style violation. In fact, it is used in the Python standard library; see the multiprocessing.heap.Heap() implementation for example:

def malloc(self, size):
    # return a block of right size (possibly rounded up)
    assert 0 <= size < sys.maxsize
    if os.getpid() != self._lastpid:
        self.__init__()                     # reinitialize after fork

之后重新初始化

threading.local 实现,它使用上下文管理器推迟初始化。

or the threading.local implementation, which uses a context manager to defer initialisation.

否则没有什么特别的关于 __ init __ 方法本身。它只是由 type .__ call __ 自动调用的(在使用 instance = cls .__ new __(cls,* args,** kwargs)创建实例后 cls .__ init __(实例,* args,** kwargs)被调用)。

There is otherwise nothing special about the __init__ method itself. It is merely automatically called by type.__call__ (after creating the instance with instance = cls.__new__(cls, *args, **kwargs), cls.__init__(instance, *args, **kwargs) is called if it is available).

这篇关于可以将__init__用作初始化的常规方法,而不用作构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆