从 NamedTuple 类继承?

问题描述

我最初的愿望是让一个类继承自 NamedTuple:首先以 NamedTuple 的方式启动它,然后执行一个没有参数的函数。为了示例起见,我们将 3D 向量和最终操作视为归一化。这是代码

from collections import namedtuple
from math import sqrt

Vector1 = namedtuple("Vector1","x y z")
# a namedtuple class that represents 3D vectors

class Vector2:
    '''a class that represents 3D vectors'''
    def __init__(self,x,y,z):
        self.x = x
        self.y = y
        self.z = z

    def __str__(self):
        return f"{self.x:.2f} {self.y:.2f} {self.z:.2f}"


class Unit1(Vector1):
    '''a namedtuple class representing a 3D vector,that 
normalizes itself at construction'''
    def __init__(self,*args):
        super().__init__(*args)
        norm = sqrt(self.x**2 + self.y**2 + self.z**2)
        self.x /= norm
        self.y /= norm
        self.z /= norm


class Unit2(Vector2):
    '''a class representing a 3D vector,that normalizes itself 
at construction'''
    def __init__(self,*args):
        super().__init__(*args)
        norm = sqrt(self.x**2 + self.y**2 + self.z**2)
        self.x /= norm
        self.y /= norm
        self.z /= norm

c = Vector1(2,3,4)
print(c)

c = Vector2(2,4)
print(c)

c = Unit2(2,4)
print(c)

c = Unit1(2,4) # fails
print(c)

它返回:

Vector1(x=2,y=3,z=4)
2.00 3.00 4.00
0.37 0.56 0.74
Traceback (most recent call last):
  File "test.py",line 46,in <module>
    c = Unit1(2,4) # fails
  File "test.py",line 21,in __init__
    super().__init__(*args)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)

令我困惑的是基类(Vector1Vector2)如何接受相同的参数,而子类却有不同的行为(即 Unit2 按预期工作,但 {{1 }} 调用 Unit1 失败)。如何解释这一点,以及如何修复 super().__init__() 使其表现得像 Unit1 而不必重新定义笨拙的自制 Unit2

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...