简体   繁体   中英

AttributeError: 'set' object has no attribute 'b'

I have the following code:

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))

With typical input, the list b looks like this:

b = ['intersection_update', '10']

What is the issue with ab[0](c) ? Apparently I am not evaluating it correctly.

The concept seems fine, but it seems like set a is not able to take an attribute which is actually an element of a list.

what I want to evaluate is:

a.intersection_update(c)

Here's the error I get:

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

I think you want to use getattr , to get an attribute who's name stored as a string in another variable:

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

Your current code is looking for an attribute named b on the a set.

You can't do that kind of indirect attribute access using the dot operator in Python. Use getattr() instead:

>>> 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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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