class 中正确的 __init__ 定义继承自 "list"
proper __init__ definition in class inherited from "list"
我正在尝试为我的 class 继承自列表定义 "the good way" 初始化函数。这是最基本的代码(我只保留了必要的代码):
class measurementPoint(list) :
"""measurementPoint class : contains all the pairedMeasurement at a given temperature for a given channel"""
def __init__(self, item):
try:
assert isinstance(item,pairedMeasurement)
except AssertionError:
print("Wrong type for object " + str(item))
sys.exit(1)
super().__init__(self)
self.append(item)
有没有比 super().__init__
后接 append
更好的初始化此类对象的方法?我想应该有一个,但不知道怎么做。
您可以将项目作为可迭代对象传递给 super().__init__
:
>>> class A(list):
def __init__(self, item):
super().__init__([item])
...
>>> a = A(100)
>>> a
[100]
我正在尝试为我的 class 继承自列表定义 "the good way" 初始化函数。这是最基本的代码(我只保留了必要的代码):
class measurementPoint(list) :
"""measurementPoint class : contains all the pairedMeasurement at a given temperature for a given channel"""
def __init__(self, item):
try:
assert isinstance(item,pairedMeasurement)
except AssertionError:
print("Wrong type for object " + str(item))
sys.exit(1)
super().__init__(self)
self.append(item)
有没有比 super().__init__
后接 append
更好的初始化此类对象的方法?我想应该有一个,但不知道怎么做。
您可以将项目作为可迭代对象传递给 super().__init__
:
>>> class A(list):
def __init__(self, item):
super().__init__([item])
...
>>> a = A(100)
>>> a
[100]