【问题标题】:what is python doing with my constructor parameters?python 对我的构造函数参数做了什么?
【发布时间】:2012-05-10 15:10:50
【问题描述】:

好的,我认为这样的代码不会出错,但它显然会出错:

somewhere:
    # p is a float value between 0 and 1
    m.limit=PidRange(p-1.0, p+1.0)

class PidRange(Range):
    def __init__(self, low, up):
        Range.__init__(low,up,...)
        pass
    # some methods definition for the PidRange sub-class

class Range(object):
    def __init__(self, p_min=None, p_max=None, ...):
        if (p_min > p_max):
             raise ValueError("Range can't be created: the low bound %f exceeds high bound %f."%(p_min,p_max))

我只是想用一些类层次结构初始化一个 [min,max] 范围。但由于一些完全奇怪的原因,p=0.888337 将 引发以下异常:

    File "src/__main__.py", line 155, in __find_data
        m.limit=PidRange(p-1.0, p+1.0)
    File "src/routing.py", line 32, in __init__
       Range.__init__(low, up, low!=None, up!=None)
    File "src/equation.py", line 30, in __init__
       raise ValueError("Range can't be created: the low bound %f exceeds high bound %f."%(p_min,p_max))
    ValueError: Range can't be created: the low bound 1.888337 exceeds high bound 1.000000.

有人知道发生了什么吗?我不得不承认我离掌握 Python 语言还很远,但我看不出任何可以解释这种奇怪行为的微妙之处。

【问题讨论】:

    标签: python inheritance constructor python-3.x


    【解决方案1】:

    啊。想通了。

    • 在对超类的__init__ 调用中缺少self
    • 1.000 'extra value' 是一个 True,从 ... 转换为浮点数

    所以超类构造函数调用“破坏”调用模型并需要显式自引用,嗯?

    【讨论】:

    • 我想如果我在检查并引发错误之前使用 self.__something 会更容易调试...
    • 它不会破坏调用模型。 Python 方法在实例上调用时将实例作为第一个参数。但是由于您是从类中调用的,因此您必须显式传递实例。如果您觉得这很奇怪,您可以改用“super”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 2018-12-31
    相关资源
    最近更新 更多