English 中文(简体)
计算机操作员和索引
原标题:Class accessible by iterator and index

我的班子执行主持人,以便我能够做到:

for i in class():

但是,我也希望能够按指数进入这一类:

class()[1]

我如何能够这样做?

最佳回答

http://docs.python.org/app/datamodel.html#object.__iter_rel=“noreferer”> 除其他外,方法。

问题回答

The present accepted accreditation/a> from @Ignacio Vazquez-Abrams is sufficient. 然而,对该问题有兴趣的其他人可能希望考虑从中继承其类别(ABC>)。 (例如 标准模块 Collections.abc。) 做一些事情(,可能还有其他物品():

  • ensures that all of the methods you need to treat your object "like a ____" are there
  • it is self-documenting, in that someone reading your code is able to instantly know that you intend your object to "act like a ____".
  • allows isinstance(myobject,SomeABC) to work correctly.
  • often provides methods auto-magically so we don t have to define them ourselves

(请注意,除上述外,重订您自己的代码><>>可允许您测试在任何物体中是否存在一种特定方法或一套方法,并以此为基础宣布该物体为的子类,even>,条件是该物体不继承>>>>s://stackover.com/a/a/193/281/14614> 见关于更多信息的答复:


Example: implement a read-only, list-like class using ABC

现在就是一个例子,请选择并实施原问题类别中的“/code>。 所需经费有两个:

  1. the class is iterable
  2. access the class by index

显然,这一类别将是某种收集。 因此,我们将研究我们的menu of Collection/code>ABC s,以找到适当的ABC。 (注还有vidic ABCs 。 适当的<代码>ABC取决于我们想要在本类别中使用的何种抽象方法。

我们看到。 如果我们想使用<代码>__iter__()(>),那么,我们就需要这样做,以便做像这样的事情:。 然而,Iterable并不包括__getitem__(),这是我们需要做的,例如myobject[i]。 因此,我们需要使用不同的<代码>ABC。

On down the collections.abc menu of abstract base classes, we see that a Sequence is the simplest ABC to offer the functionality we require. And - would you look at that - we get Iterable functionality as a mixin method - which means we don t have to define it ourselves - for free! We also get __contains__, __reversed__, index, and count. Which, if you think about it, are all things that should be included in any indexed object. If you had forgotten to include them, users of your code (including, potentially, yourself!) might get pretty annoyed (I know I would).

然而,有第二个<代码>ABC,该编码还提供了这种功能组合(可操作,并可通过<代码>查询):/code><><>>>>>>。 我们想要使用什么?

我们回顾,要求能够查阅by index。 (如list tuple,即notby key (如dict)。 因此,我们选择<代码>Sequence而不是Mapping


旁边: 必须指出,<代码>Sequence是读取的(如Mapping/code>),因此,它不允许我们做诸如myobject[i] = 价值random.shuffle(myobject)等事情。 如果我们想要能够做这样的事情,我们需要继续缩小<代码>的菜单。 ABC s and use a >:code>MutableSequence (or a


Example Code

现在,我们能够做我们的工作。 我们对此加以定义,并继承<条码>。

from collections.abc import Sequence

class MyClass(Sequence):
    pass

如果我们尝试使用这种方法,口译人员将告诉我们,在使用这种方法之前,我们需要采用哪些方法(指出这些方法也列在“灰色”一页):

>>> myobject = MyClass()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can t instantiate abstract class MyClass with abstract methods __getitem__, __len__

这告诉我们,如果我们走到前面,执行<条码>——项目__和<条码>_len__,我们就能够使用我们的新类别。 我们可能这样做。

from collections.abc import Sequence

class MyClass(Sequence):
    def __init__(self,L):
        self.L = L
        super().__init__()
    def __getitem__(self, i):
        return self.L[i]
    def __len__(self):
        return len(self.L)

# Let s test it:
myobject = MyClass([1,2,3])
try:
    for idx,_ in enumerate(myobject):
        print(myobject[idx])
except Exception:
    print("Gah! No good!")
    raise
# No Errors!

It works!





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...