English 中文(简体)
甲型六氯环己烷——使用钥匙从名单中获取一分
原标题:Python - Access a class from a list using a key
  • 时间:2010-04-05 08:42:24
  •  标签:
  • python
  • class

是否有办法把班级清单同在座的一组一样?

基本上,Im公司在一部分软件上工作,有些软件涉及细化比较,而我有一个处理插座的定制类别。 因此,每一次扼杀都有一类。

因此,我有一个包含所有这些类别的大名单。 我想能够查阅list[key],在这种情况下,关键在于扼杀这几类人(注:一旦上课,便永远不会改变这种说法,因此应该保持沉默)。

在我看来,我可以稍微方便地做这项工作,在表格中添加诸如<条码>_cmp__<>/code>等内容,但Im 是过时的(类似),或Im在笔中遗漏一些东西。

基本上,我希望能够做这样的事情(大事就是:

>>class a:
... def __init__(self, x):
...  self.var = x
...
>>> from test import a
>>> cl = set([a("Hello"), a("World"), a("Pie")])
>>> print cl
set([<test.a instance at 0x00C866C0>, <test.a instance at 0x00C866E8>, <test.a instance at 0x00C86710>])
>>> cl["World"]
<test.a instance at 0x00C866E8>

感谢!

增 编 Tweaks:

class a:
... def __init__(self, x):
...     self.var = x
... def __hash__(self):
...     return hash(self.var)
...
>>> v = a("Hello")
>>> x = {}
>>> x[v]=v
>>> x["Hello"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError:  Hello 
>>> x["Hello"]
最佳回答

仅写一个像地图这样的行业:

class ClassDict(object):
  def __init__(self):
    self.classes = {}

  def add(self, cls):
    self.classes[cls.__name__] = cls

  def remove(self, cls):
    if self.classes[cls.__name__] == cls:
      del self.classes[cls.__name__]
    else:
      raise KeyError( %r  % cls)

  def __getitem__(self, key):
    return self.classes[key]

  def __repr__(self):
    return  ClassDict(%s)  % ( ,  .join(self.classes),)

class C(object):
  pass

class D(object):
  pass

cd = ClassDict()
cd.add(C)
cd.add(D)

print cd

print cd[ C ]
问题回答

为什么不要让你去做:

>>> v = MyStr("Hello")
>>> x = {}
>>> x[v.val]=v
>>> x["Hello"]
MyStr("Hello")

为什么要抓住一切困难,试图制造一种使用与你所穿的钥匙不同的手脚dict? (即“Hello”而不是MyStr(“Hello”))。

页: 1

class MyStr(object):
    def __init__(self, val):
        self.val = str(val)

    def __hash__(self):
        return hash(self.val)

    def __str__(self):
        return self.val

    def __repr__(self):
        return  MyStr("%s")  % self.val


>>> v = MyStr("Hello")
>>> x = {}
>>> x[str(v)]=v
>>> x["Hello"]
MyStr("Hello")

计算和定本使用物体_hash_退回的价值 寻找目标的方法,这样,你就能够做:

>>class a:
... def __init__(self, x):
...  self.var = x
...
... def __hash__(self):
...  return hash(self.var)

由于我记得“定型”和“定型”用途也有<代码>hash__。

http://docs.python.org/library/stdtypes.html#mapping-types-dict”rel=“nofollow noreferer”>Python 2.x doc:

字典的关键是a 近任意的数值。 不是hashable,即含有清单、字典或其他变型的数值(按价值而不是物体特性加以比较)不得用作钥匙。

你们想要的是这样的东西。

class A(object):
    ALL_INSTANCES = {}
    def __init__(self, text):
        self.text = text
        self.ALL_INSTANCES[self.text] = self



a1 = A("hello")
a2 = A("world")

print A.ALL_INSTANCES["hello"]

产出:

<__main__.A object at 0x00B7EA50>




相关问题
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 ]="...

热门标签