我如何使自定义类在Python中的集合 [英] How do I make a custom class a collection in Python

查看:716
本文介绍了我如何使自定义类在Python中的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自一个Matlab背景。在matlab中,我可以创建一个类定义,然后创建一个对象数组。我可以很容易地解引用每个对象与索引。此外,当我从对象数组(没有索引)调用方法时,我可以访问数组中的所有对象。例如,说myNewClass有属性.data和.text,它也有方法.clob。我可以:

I come from a Matlab background. In matlab I can create a class definition and then create an array of objects. I can easily dereference each object with an index. In addition, when I call a method from the object array (without an index), I have access to all the objects in the array. E.g, say that myNewClass has the properties .data and .text, it also has the method .clob. I can:

% init
a(1) = myNewClass;
a(2) = myNewClass;

a(1).data = [0;0;0];
a(2).data = [1;1;1];

现在,如果我调用a.clob(不是(1).clob或a 2).clob),我可以做类似

So that now, if I call a.clob (not a(1).clob or a(2).clob), I can do something like

% 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中做这样的事情?请注意,我希望我的班级是一个索引集合,有点像一个列表。但是,我不想让我的类列表接受任何类,只是myNewClass。如果我继承list,我的类将只是一个具有属性.data,.text和函数.clob的list类。还要注意,我不想要一个包含我的对象的列表,我想我的对象列表,以便我可以deref他们从索引:a [1] .clob()或a(1).clob ) (?? 或类似的东西)。或者,我想将整个数组传递给self:a.clob()让我访问列表。

How do I do something like this in Python? Please note, I want my class to be an indexed collection, kind of like a list. But, I don't want my "class-list" to accept any class, just myNewClass. If I inherit from "list," will my class just be a "list" class with the attributes .data, .text, and the function .clob? Also note, I don't want a "list" that contains my objects, I want my objects to be list so that I can deref them from an index: a[1].clob() or a(1).clob() (?? or something like that). Or, I want to pass the whole array to self: a.clob() gives me access to the list. I may have the terminology a little cloudy.

最好的祝福

推荐答案

Python中的所有这些功能使用特殊方法名称,如语言参考部分3.3中所述。第3.3.6节描述了如何模拟容器类型,这通常是你在这里要求的。您需要定义和实现方法 __ getitem __ __ setitem __ __ delitem __ 也可以 __ iter __ __ reversed __ __包含__ 。 Python是相当不错的,这种方法非常灵活。

All such capabilities in Python use "Special method names" as described in the Language Reference section 3.3. Section 3.3.6 describes how to emulate container types, which in general is what you're asking for here. You need to define and implement methods __getitem__, __setitem__,__delitem__ and perhaps also __iter__, __reversed__ and __contains__. Python is quite good for this and the approach is very flexible.

这篇关于我如何使自定义类在Python中的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆