[英]Python how to find an object by its attributes?
Is there a way to get an object by matching it up with its attributes? 有没有办法通过将对象与其属性进行匹配来获取对象? For example: 例如:
class band:
def __init__(self, name, number):
self.name = name
self.number = number
rivers = band("rivers", 1)
patrick = band("pat" , 2)
brian = band("brian" , 3)
scott = band("scott", 4)
In this code, is there a way for me to use a number(lets say 1), to find the object rivers within the band class and get its name attribute? 在这段代码中,有没有办法让我使用一个数字(比方说1),找到band类中的对象河流并获取其name属性?
Thank you for taking your time to read this and have a nice day. 感谢您抽出宝贵时间阅读本文,祝您度过愉快的一天。
In this code, is there a way for me to use a number(lets say 1), to find the object rivers within the band class and get its name attribute? 在这段代码中,有没有办法让我使用一个数字(比方说1),找到band类中的对象河流并获取其name属性?
In this code, NO. 在这段代码中,NO。 Because you do not save the value of name
to the class property. 因为您没有将name
的值保存到class属性中。
However, if your class structure was like: 但是,如果您的类结构如下:
class band:
def __init__(self, name, number):
self.number = number
self.name = name # <--- Here is the difference
you could have done it. 你本可以做到的。 Let say rivers
, patrick
, brian
and scott
are part of the list as: 让rivers
, patrick
, brian
和scott
成为名单的一部分:
my_list = [rivers, patrick, brian, scott]
Iterate over the list and print the name
of class for which value of number
is 1
as: 遍历列表并打印number
值为1
的类的name
:
for item in my_list:
if item.number == 1:
print item.name
You may store a dictionary mapping number to band in order to achieve that. 您可以将字典映射编号存储到band以实现该目的。
For example 例如
bands = {}
class band:
def __init__(self, name, number):
self.number = number
self.name = name
bands[number] = self
def getBandFromNumber(number):
return bands[number]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.