Subklassige Q_ im Pint - Warum nimmt der Super -Anruf keine Argumente an?Python

Python-Programme
Anonymous
 Subklassige Q_ im Pint - Warum nimmt der Super -Anruf keine Argumente an?

Post by Anonymous »

(Python 3.7) < /p>

Pint /q_ Verhalten < /strong> < /p>

Ich möchte die Menge der Menge des Pints ​​unterklassen und __init __ < /code> überschreiben. Die Standardsyntax schlägt fehl

Code: Select all

# 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)
< /code>

Was zu funktionieren scheint, bedeutet, in der Unterklasse überhaupt nicht Super /Init zu nennen, aber wie macht das überhaupt Sinn? < /p>

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'
< /code>

Ich glaube, letzteres ist das, was ich verwenden möchte, aber mit Code, der funktioniert, wenn Sie der Meinung sind, dass es nicht funktionieren sollte, scheint ein Rezept für eine Katastrophe zu sein. Was passiert? https://github.com/hgrecco/pint/blob/master/pint/quantity.py#l1741) aber nicht feststellen, warum es eine Rolle spielt.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'
< /code>

Ohne den Aufruf von Super < /code> hat die übergeordnete Klasse keine Möglichkeit, die Argumente zu kennen, mit denen sie initialisieren soll: < /p>

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'

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post