Search code examples
pythonpython-3.xattributesindirection

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 a.b[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'

Solution

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