簡體   English   中英

對象列表中的Python返回設置了類屬性的第一個對象

[英]Python from a list of objects return the first object which has a class attribute set

給定具有屬性a和b的對象列表,我想從滿足給定約束的列表中的第一個對象獲取屬性。 下面顯示了一種解決方案,但是對於具有許多屬性的對象,這是不希望的。

class Foo(object):
  def __init__(self):
  self.a = 0
  self.b = 1

def get_first_a(l):
  return next(val.a for val in l if val.a > 0)

def get_first_b(l):
  return next(val.b for val in l if val.b > 0)

def main():
  bar0 = Foo()
  bar1 = Foo()
  bar2 = Foo()
  bar2.a = 10
  l = [bar0, bar1, bar2]
  a = get_first_a(l)  # returns 10
  b = get_first_b(l)  # returns 1

有沒有一種方法可以將對象屬性傳遞給函數? 我不希望添加枚舉或使用字符串匹配,而應遵循以下原則:

def get_first_b(l, object_attribute):
  return next(val.object_attribute for val in l if val.object_attribute != 0) 

使用getattr並為任何屬性定義一個函數

def get_first(l,attr):
  return next(getattr(val,attr) for val in l if getattr(val,attr) > 0)

您可以使用getattr,但是如果沒有滿足您條件的object_attribute,最終將產生StopIteration錯誤:

def get_first(l, object_attribute, op, cond):
    return next((getattr(val, object_attribute) for val in l
                if op(getattr(val, object_attribute), cond)), None)

您可以將任意內容傳遞給單個函數:

from operator import ne, gt, lt
def main():
    bar0 = Foo()
    bar1 = Foo()
    bar2 = Foo()
    bar2.a = 10
    l = [bar0, bar1, bar2]
    a = get_first(l,"a", gt, 0)  # returns 10
    b = get_first(l, "b", ne, 0)  # returns 1
    c = get_first(l, "b", lt, -1)
    print(a)
    print(b)
    print(c)

main()

輸出:

10
1
None

如果您知道對象中有哪些屬性,請嘗試以下操作:

# some class with properties
class Foo:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def retA(self):
        return self.a

    def retB(self):
        return self.b

# forming a list with the objects
l_b = []
l_b.append(Foo('a1','b1'))
l_b.append(Foo('a2','b2'))
l_b.append(Foo('a3','b3'))

# function to grab a property from object in list on the exact position in the list        
def getPropFormListOfObj(list_obj, position_in_list, property_obj):
"""
list_obj (type = list)- list of objects
position_in_list (type = int) - position of object in the list from 0 to (len(list_obj) - 1)
property_obj (type = str) - the property we want to return. in this implementation works only if == 'a' or 'b'
"""
    if (property_obj == 'a'):
        return list_obj[position_in_list].retA()
    elif (property_obj == 'b'):
        return list_obj[position_in_list].retB()        

# test
# expected output "a1"
print getPropFormListOfObj(l_b, 0, 'a')

# test
# expected output "b2"
print getPropFormListOfObj(l_b, 2, 'b')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM