【问题标题】:Python: How to call member functions a key of a dict when the key is an object?Python:当键是对象时,如何将成员函数称为字典的键?
【发布时间】:2013-11-29 23:27:51
【问题描述】:

在下面的示例中,我想通过调用类Aset_x() 函数来更改da1 键。但我看不到如何访问 dict 中的密钥。

#!/usr/bin/env python

class A(object):
  def __init__(self, data=''):
    self.data = data
    self.x = ''
  def set_x(self, x):
    self.x = x
  def __repr__(self):
    return 'A(%s:%s)' % (self.data, self.x)
  def __eq__(self, another):
    return hasattr(another, 'data') and self.data == another.data
  def __hash__(self):
    return hash(self.data)

a1 = A('foo')
d = {a1: 'foo'}
print d #{A(foo:): 'foo'}

我想更改d,以便d 将打印为{A(foo:word): 'foo'}。当然,以下不起作用。我也不想重新分配相同的值。有人知道通过调用密钥的成员函数来修改密钥的方法吗?谢谢。

a2 = A('foo')
a2.set_x('xxxx')
d[a2]='foo'
print d

【问题讨论】:

    标签: python class dictionary key


    【解决方案1】:

    您需要引用对象本身,并在那里对其进行修改。

    看看这个控制台会话:

    >>> a = A("foo")
    >>> d = {a:10}
    >>> d
    {A(foo:): 10}
    >>> a.set_x('word')
    >>> d
    {A(foo:word): 10}
    

    也可以从dict.items()获取键值对:

    a, v = d.items()[0]
    a.set_x("word")
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      您可以保留对对象的引用并对其进行修改。如果您不能保留对 key 对象的引用,您仍然可以使用 for k, v in d.items(): 遍历 dict,然后使用该值来知道您拥有哪个键(尽管这在如何使用 dict 方面有些落后并且效率很低)

      a1 = A('foo')
      d = {a1: 'foo'}
      print(d) # {A(foo:): 'foo'}
      a1.set_x('hello')
      print(d) # {A(foo:hello): 'foo'}
      

      【讨论】:

        猜你喜欢
        • 2021-08-12
        • 1970-01-01
        • 2021-10-02
        • 2013-08-23
        • 2018-06-12
        • 1970-01-01
        • 2012-08-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多