0

(Python 3.7)

品脱/Q_行为

我想继承品脱的数量类并覆盖__init__。标准语法失败,因为显然参数冒泡到objectinit 方法(不带参数):

# file: test.py
from pint import UnitRegistry

ureg = UnitRegistry()
Q_ = ureg.Quantity

class Q_Child_(Q_):
    def __init__(self, *args, **kwargs):
        super(Q_, self).__init__(*args, **kwargs)
        self.foo = 'foo'

a=Q_Child_(1.0, 's') # Raises an error:
# Traceback(most recent call last):
#   File ".../test.py", line 12, in < module >
#   a = Q_Child_(1.0, 's')
#   File ".../test.py", line 9, in __init__
#   super(Q_, self).__init__(*args, **kwargs)
# TypeError: object.__init__() takes exactly one argument(the instance to initialize)

似乎可行的是在子类中根本不调用 super/init ,但这有什么意义呢?

from pint import UnitRegistry

ureg = UnitRegistry()
Q_ = ureg.Quantity

class Q_Child_(Q_):
    def __init__(self, *args, **kwargs):
        # not calling super or Q_.__init__ (or so it seems)
        self.foo = 'foo'

a=Q_Child_(1.0, 's')
print(a)  # '1.0 second'  -> how does it even know the passed arguments?
print(a.foo)  # 'foo'

我相信后者是我想要使用的,但是当你认为它不应该工作时使用可以工作的代码似乎是灾难的根源。怎么了?

这是由于Q_动态生成的(ureg实例化时,请参阅https://github.com/hgrecco/pint/blob/master/pint/registry.py#L115https://github.com/hgrecco/pint /blob/master/pint/quantity.py#L1741)但看不到它为什么重要。

该问题不是使用 super (参数传递)(或类似)的正确方法的重复,因为标准方法在这里不起作用:

class NewDict(dict):
    def __init__(self, *args, foo='foo', **kwargs):
        super(NewDict, self).__init__(*args, **kwargs)
        self.foo = foo

nd = NewDict({'a': 1}, foo='bar')
print(nd)  # {'a': 1}
print(nd.foo)  # 'bar'

如果没有super调用,父类就无法知道它应该初始化的参数:

class NewDictWithoutSuper(dict):
    def __init__(self, *args, foo='foo', **kwargs):
        self.foo = foo

nd = NewDictWithoutSuper({'a': 1}, foo='bar')
print(nd)  # {} i.e. the default dict()
print(nd.foo)  # 'bar'
4

0 回答 0