简体   繁体   English

如何为对象列表返回int类型表示

[英]How to return an int type representation for a list of objects

When outputting a list of objects how can you return an int type representation for the objects? 输出对象列表时,如何返回对象的int类型表示形式?

I've tried this: 我已经试过了:

class Passport(object):
    def __init__(self, my_id):
        self.id = my_id

    def __repr__(self):
        return int(self.id)



list_of_objects = [
Passport(19181),
Passport(29191),
Passport(39191)
]

if id in list_of_objects:
    print("true")

Where list_of_objects is a list of Passport instances. 其中list_of_objects是Passport实例的列表。 But this gives an error __repr__ returned non-string (type int) . 但这会导致错误__repr__ returned non-string (type int)

I could solve this problem using a string for both, but I'm wondering if type int is possible? 我可以同时使用字符串来解决此问题,但我想知道是否可以使用int类型?

__repr__ is required to return a string representation of the object. 需要 __repr__返回对象的字符串表示形式。 Returning a different type is not a valid implementation of __repr__ . 返回其他类型不是__repr__的有效实现。

If you want a way to return some number, then add a custom method that does that. 如果您想要一种返回一些数字的方法,请添加一个执行该操作的自定义方法。

Btw., note that implementing __repr__ is not a way to make id in list_of_objects work. 顺便说一句,请注意,实现__repr__并不是使id in list_of_objects起作用的方法。 For that to work, you should implement __hash__ and __eq__ . 为此,您应该实现__hash____eq__ But at that point, you should really think about if you want 5 == Passport(5) to be true; 但是到那时,您应该真正考虑是否要让5 == Passport(5)为真; probably not. 可能不是。 So you should change the way your check works by explicitely looking at the id property instead. 因此,您应该通过显式查看id属性来更改检查的工作方式。

Instead of if id in list_of_objects , you could do the following: 除了if id in list_of_objects ,还可以执行以下操作:

if any(lambda x: x.id == id, list_of_objects):
    print('true')

You could check a parallel list of the object ids instead. 您可以改为检查对象ID的并行列表。

if any(id == pp.id for pp in list_of_objects):
    print("true")

__repr__ must return a str as you have seen. 如您所见, __repr__必须返回一个str

The proper way to do what you are asking is: 做您要问的正确方法是:

list_of_object_ids = [p.id for p in (Passport(19181), Passport(29191), Passport(39191))]
if id in list_of_objects:
    print("true")
class Passport(object):
    def __init__(self, my_id):
        # It is recommended to call int here also in order to prevent
        # construction of invalid objects.
        self.id = int(my_id)

    def __int__(self):
        return int(self.id)

list_of_objects = [
Passport(19181),
Passport(29191),
Passport(39191)
]

list_of_ints = [int(passport) for passport in list_of_objects]

if id in list_of_ints:
    print("true")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM