2017-09-29 51 views
0

我有以下代碼:AttributeError的: '設置' 對象有沒有屬性 'B'

N1 = int(input()) 
a = set(list(map(int, input().split()))) 
N2 = int(input()) 
for i in range(N2): 
    b = input().split() 
    c = set(list(map(int, input().split()))) 
    a.b[0](c) 
print(sum(a)) 

對於典型的輸入,列表b看起來是這樣的:

b = ['intersection_update', '10'] 

問題是什麼與a.b[0](c)?顯然,我沒有正確評估它。

這個概念看起來很好,但它看起來像設置a是不能夠採取一個實際上是一個列表元素的屬性。

我要評價是:

a.intersection_update(c) 

這裏的錯誤,我得到:

Traceback (most recent call last): 
    File "solution.py", line 7, in 
    a.b[0](c) 
AttributeError: 'set' object has no attribute 'b' 

回答

1

您不能在Python中使用點運算符進行那種間接屬性訪問。使用getattr()代替:

>>> a = {1, 2, 3, 4, 5} 
>>> c = {3, 4, 5, 6, 7} 
>>> b = ['intersection_update', '10'] 
>>> getattr(a, b[0])(c) 
>>> a 
{3, 4, 5} 
+1

感謝,它的工作。我今天學了些新東西 :) – hky404

1

我想你想使用getattr,讓誰的存儲爲一個字符串名稱的屬性另一個變量:

getattr(a, b[0])(c) 

您當前的代碼正在查找名爲的屬性在a集。

相關問題