Python,将非字符串对象表示为字符串?

Python,将非字符串对象表示为字符串?

我想将一个对象表示为一个字符串,以便它既可以作为字典键也可以作为对象访问。即

class test(object):
 def __init__(self, name, number_array): 
     self.name = name
     self.number_array = number_array
     self.graph= barChart(number_array) 

sample_obj = test('test_object', [(x1,y1), (x2,y2)etc.])

{sample_obj: another_object}看起来像{'test_object': another_object}

虽然仍然可以做这样的事情:

for key, val in sample_dict.items(): print(key.name, key.graph)

以及:

>>> sample_dict['test_object']
another_object

最佳答案:

2 个答案:

答案 0 :(得分:1)

要将类用作字典键,请实现__hash____eq__。要在打印字典时更改的显示方式,请实施__repr__

class Test(object):

    def __init__(self, name, number_array): 
        self.name = name
        self.number_array = number_array
        self.graph = barChart(number_array) 

    def __eq__(self, other):
        return self.name == other.name and self.number_array == other.number_array

    def __hash__(self):
        return hash(self.name) ^ hash(self.number_array)

    def __repr__(self):
        return "test_object"

使用中:

>>> t = Test("foo", (1, 2, 3))
>>> d = {t: [1, 2, 3]}
>>> t
test_object
>>> d
{test_object: [1, 2, 3]}
>>> d[t]
[1, 2, 3]

请注意,这意味着namenumber_array属性都必须是可清除的 - 我使用了字符串和元组来确保这一点。此外,如果__repr__更接近地表示实际对象,例如

,则会更好

def __repr__(self):
    return "Test({0.name!r}, {0.number_array!r})".format(self)

答案 1 :(得分:1)

您必须定义 eq ,在与字符串比较时返回正数,例如:

def __eq__(self, other):
    if self.name == other:
        return True
    ... continue with comparison ...

您还必须定义哈希,它返回与比较字符串相同的哈希值:

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

更新:以下代码完全符合作者的要求:

class test(object):
    def __init__(self, name, number_array): 
        self.name = name
        self.number_array = number_array
        #self.graph= barChart(number_array)

    def __eq__(self, other):
        try:
            return (self.name == other.name) and (self.number_array == other.number_array)
        except AttributeError:
            return self.name == other

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

sample_obj = test('test_object', [(0, 1), (2, 3)])

dict1 = {sample_obj: "Hurray"}
print("dict1[sample_obj]", dict1[sample_obj])
print("dict1['test_object']", dict1['test_object'])

dict2 = {'test_object': "Yippie"}
print("dict2[sample_obj]", dict2[sample_obj])
print("dict2['test_object']", dict2['test_object'])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值