我有 Matlab 背景。在 matlab 中,我可以创建一个类定义,然后创建一个对象数组。我可以轻松地使用索引取消引用每个对象。此外,当我从对象数组(没有索引)调用方法时,我可以访问数组中的所有对象。例如,假设 myNewClass 具有属性 .data 和 .text,它还有方法 .clob。我可以:
% init
a(1) = myNewClass;
a(2) = myNewClass;
a(1).data = [0;0;0];
a(2).data = [1;1;1];
所以现在,如果我调用 a.clob(不是 a(1).clob 或 a(2).clob),我可以做类似的事情
% this is a function inside the methods definition of my class definition
function clob(self)
% self here is my object array, "a", from above
for i=1:length(self)
% deref a single object
self(i).goClobYourself;
end
end
我如何在 Python 中做这样的事情?请注意,我希望我的类(class)成为一个索引集合,有点像列表。但是,我不希望我的“类(class)列表”接受任何类(class),只接受 myNewClass。如果我从“列表”继承,我的类是否只是一个具有属性 .data、.text 和函数 .clob 的“列表”类?另请注意,我不想要包含我的对象的“列表”,我希望我的对象是列表,以便我可以从索引中取消引用它们:a[1].clob() 或 a(1).clob( ) (?? 或类似的东西)。或者,我想将整个数组传递给自己:a.clob() 让我可以访问列表。我的术语可能有点模糊。
最好的问候
最佳答案
在使用 Python 编程时,执行类型检查并不常见。您确定您需要您的列表只接受一种类型(及其子类型),还是您会相信程序员会阅读您的文档并且不会放入不应该存在的内容?
如果是这样,下面是一个继承自 collections.MutableSequence
的示例泛型类,它可能会执行您想要的操作:
from collections import MutableSequence
class VerifierList(MutableSequence):
_list = None
def __init__(self, allowedClasses, *args, **kwargs):
super(VerifierList, self).__init__()
self._list = list(*args, **kwargs)
self.allowedClasses = tuple(allowedClasses)
def __repr__(self):
return repr(self._list)
def __str__(self):
return str(self._list)
def __len__(self):
return len(self._list)
def __getitem__(self, index):
return self._list[index]
def __setitem__(self, index, value):
if not isinstance(value, self.allowedClasses):
raise TypeError('Value of type %s not allowed!' % value.__class__.__name__)
self._list[index] = value
def __delitem__(self, index):
del self._list[index]
def insert(self, index, value):
if not isinstance(value, self.allowedClasses):
raise TypeError('Value of type %s not allowed!' % value.__class__.__name__)
self._list.insert(index, value)
按如下方式使用:
>>> class A(object): pass
>>> class B(object): pass
>>> l = VerifierList((A,))
>>> l.append(A())
>>> print(l)
>>> [<__main__.A object at 0x000000000311F278>]
>>> l.append(B())
Traceback (most recent call last):
File "<pyshell#228>", line 1, in <module>
l.append(B())
File "C:\Python27\lib\_abcoll.py", line 661, in append
self.insert(len(self), value)
File "<pyshell#204>", line 23, in insert
raise TypeError('Value of type %s not allowed!' % value.__class__.__name__)
TypeError: Value of type B not allowed!
关于python - 如何使自定义类成为 Python 中的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31528933/