微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 NamedTuple 类继承?

如何解决从 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.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?