[英]python getting a specific attribute from a list of objects
我有一個對象的python數組
class ball(self, size, color, name):
self.size = size
self.color = color
self.name = name
用戶將通過命令行輸入名稱和屬性。 例如,用戶可以輸入“ name1”,然后輸入“ color”或“ weirdName”,然后輸入“ size” ...然后,我想根據名稱查找對象並打印得到顏色對象或size對象。 我可以這樣做嗎,還是需要使用開關盒?
謝謝
如果您知道完全匹配,則可以執行以下操作:
the_ball = next(b for b in list_of_balls if b.name == ???)
如果有多個,則可以得到一個列表:
the_balls = [b for b in list_of_balls if b.name == ???]
如果您主要是按照球的名稱查找球,則應將其保留在詞典中而不是列表中
要通過名稱檢索屬性,請使用getattr
getattr(the_ball, "size")
這樣做可能不是一個好主意
getattr(the_ball, user_input)
如果user_input是"__class__"
或其他您沒想到的東西怎么辦?
如果只有幾種可能性,最好明確
if user_input == "size":
val = the_ball.size
elif user_input in ("colour", "color"):
val = the_ball.color
else:
#error
我認為您正在嘗試在這里做兩種不同的事情。
首先,您想按名稱獲取特定的球。 為此,gnibbler已經為您提供了答案。
然后,您想按名稱獲取球的屬性之一。 為此,請使用getattr
:
the_ball = next(b for b in list_of_balls if b.name == sys.argv[1])
the_value = getattr(the_ball, sys.argv[2])
print('ball {}.{} == {}'.format(sys.argv[1], sys.argv[2], the_value)
另外,您的class
定義是錯誤的:
class ball(self, size, color, name):
self.size = size
self.color = color
self.name = name
您可能打算將其作為ball
類內部的__init__
方法,而不是class
定義本身:
class ball(object):
def __init__(self, size, color, name):
self.size = size
self.color = color
self.name = name
但是,您可能需要重新考慮您的設計。 如果通過名稱動態訪問屬性的頻率要比直接訪問屬性的頻率高,那么通常最好是存儲一個dict
。 例如:
class Ball(object):
def __init__(self, size, color, name):
self.name = name
self.ball_props = {'size': size, 'color': color}
list_of_balls = [Ball(10, 'red', 'Fred'), Ball(20, 'blue', 'Frank')]
the_ball = next(b for b in list_of_balls if b.name == sys.argv[1])
the_value = the_ball.ball_props[sys.argv[2]]
或者,您甚至可能希望繼承自dict
或collections.MutableMapping
或其他內容,因此您可以執行以下操作:
the_value = the_ball[sys.argv[2]]
另外,您可能要考慮使用按名稱鍵入的球的dict
,而不是列表:
dict_of_balls = {'Fred': Ball(10, 'red', 'Fred'), …}
# ...
the_ball = dict_of_balls[sys.argv[1]]
如果您已經構建了list
,那么可以很容易地從中構建dict
:
dict_of_balls = {ball.name: ball for ball in list_of_balls}
如果我理解正確,則需要根據屬性值從球列表中獲取特定球。 一個解決方案是:
attribute_value = sys.argv[1]
attribute_name = sys.argv[2]
matching_balls = [ball_item for ball_item in list_balls if \
getattr(ball_item, attribute_name) == attribute_value]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.