如何解决从 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)
令我困惑的是基类(Vector1
和 Vector2
)如何接受相同的参数,而子类却有不同的行为(即 Unit2
按预期工作,但 {{1 }} 调用 Unit1
失败)。如何解释这一点,以及如何修复 super().__init__()
使其表现得像 Unit1
而不必重新定义笨拙的自制 Unit2
?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。