从__init __()调用重写的方法是否安全?
这是来自此问题的后续内容:
有效的Java 2nd Edition,第17项:继承的设计和文档,或者禁止继承:
一个类还必须遵守一些其他限制才能允许继承.构造函数不得直接或间接调用可重写的方法.如果违反此规则,将导致程序失败.超类构造函数在子类构造函数之前运行,因此子类中的重写方法将在子类构造函数运行之前被调用.如果重写方法依赖于子类构造函数执行的任何初始化,则该方法将无法正常工作.
There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will be invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.
由于我们仅涉及Java构造函数的初始化方面,因此我认为在这个问题中将Java的构造函数与Python的 __ init __()
进行比较是安全的.
Since we are only going to touch the initialization aspect of the Java's constructor, I assume it's safe to compare Java's constructor with Python's __init__()
in this question.
我正在猜测,因为在 Python
中,我可以灵活地决定何时调用祖先的 __ init __()
(在这种情况下,在初始化当前类的数据属性之后)与Java相比,在Java中 super()
必须是构造函数调用中的第一条语句,我可以从 __ init __()
调用重写的方法吗?
I am guessing since in Python
I have the flexibility to decide when to call (after initializing my current class' data attributes in this case) my ancestor's __init__()
as compared to Java where super()
needs to be the first statement in a constructor's invocation, I might be safe in calling overridden methods from __init__()
?
如果我对上述说法的猜测是正确的,作为祖先类设计师,我是否会不理会子类设计师的摆布?如果子类设计器在初始化将由他的一个重写方法使用的数据属性之前调用我的 __ init __()
,并且我调用该方法,则会导致程序失败!
If I am correct in guessing the aforementioned, wouldn't I as an ancestor class designer getting left at the mercy of my subclass designer? If the subclass designer calls my __init__()
before he initializes his data attributes which will be used by one of his overridden methods, and I call that method, I result in program failure!
我可以安全地从
__ init __()
调用重写的方法吗?
你是.在评估 __ init __()
之前,已经发生了 self
绑定.
You are. The self
binding has already happened before __init__()
is evaluated.
祖先类的设计师会被我的子类设计师所摆布吗?
ancestor class designer getting left at the mercy of my subclass designer?
这是普遍的说法,与 __ init __()
或其他任何内容都无关.
That's universally true and has nothing to do with __init__()
or anything else.
子类开发人员可以执行任何操作.另外,这是Python:他们有您的源代码,也可以对其进行修改.
Subclass developers can do anything. Also, this is Python: they have your source, and can modify that also.
如果子类设计器在初始化将由他的一个重写方法使用的数据属性之前调用我的
__ init __()
,并且我调用该方法,则会导致程序失败!
If the subclass designer calls my
__init__()
before he initializes his data attributes which will be used by one of his overridden methods, and I call that method, I result in program failure!
正确.发生这种情况的方式是子类设计器选择了您已经已使用的名称.他们保证程序不会因选择名称而失败.
Correct. The way this will happen is the subclass designer picked a name which you were already using. They assured that the program would fail through their choice of name.