[英]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.