简体   繁体   English

当在 Python 中给出类属性之一的值时,如何访问列表中的类对象?

[英]How to access a class object inside a list when a value for one of the class attributes is given in Python?

I have a list of class objects and I want to know how can I print a particular class object inside the list given a value for one of its attributes.我有一个类对象列表,我想知道如何在列表中打印一个特定的类对象,给它一个属性的值。

Here is my code:这是我的代码:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

lst = [Person("A",1), Person("B",2), Person("C", 3)]

inputAge = int(input("Age: "))

if inputAge == 2:
  print() #this should print the class object with age 2 from the list 

I don't know what should I put inside the print() code.我不知道我应该在print()代码中放什么。

This is how you can find the first element of the list having a specific attribute (precondition: all objects of the list have that attribute):这是您可以找到具有特定属性的列表的第一个元素的方法(前提条件:列表的所有对象都具有该属性):

obj = next((x for x in lst if x.age == inputAge), None)

obj is None if such an object can't be found in the list.如果在列表中找不到这样的对象,则objNone

Once you found the object, you can do whatever you want with it, including printing ( print(obj) ).找到对象后,您可以对它做任何您想做的事情,包括打印( print(obj) )。

If you want the printing of the object to be meaningful you would have to do something like this:如果您希望对象的打印有意义,则必须执行以下操作:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  def __str__(self):
    return 'name: ' + self.name + ' age: ' + self.age

This is the complete example:这是完整的例子:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  def __str__(self):
    return 'name: ' + self.name + ' age: ' + self.age

lst = [Person("A",1), Person("B",2), Person("C", 3)]

inputAge = int(input("Age: "))
obj = next((x for x in lst if x.age == inputAge), None)
print(obj) # prints the object with age = inputAge

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

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