0

Here is a code I have written. I presumed both of them to return the same answer but they don't! How are they different?

from collections import deque
d = deque()
for _ in range(int(input())):
    method, *n = input().split()
    getattr(d, method)(*n)
print(*d)

and

from collections import deque
d = deque()
for _ in range(int(input())):
    method, *n = input().split()
    d.method(*n)
print(*d)
  • 1
    They are completely different. `d` is a `deque` object, and doesn't have a `.method` attribute. Note, this does not involve the variable, `method` at all. – juanpa.arrivillaga Jun 07 '21 at 02:18

1 Answers1

2

getattr(...) will get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.

Where as d.method(*n) will try to lookup the method named method in deque object result in AttributeError: 'collections.deque' object has no attribute 'method'

>>> from collections import deque
>>> d = deque()
>>> dir(d) # removed dunder methods for readability
[
   "append",
   "appendleft",
   "clear",
   "copy",
   "count",
   "extend",
   "extendleft",
   "index",
   "insert",
   "maxlen",
   "pop",
   "popleft",
   "remove",
   "reverse",
   "rotate",
]
>>> method = "insert"
>>> d.method
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'collections.deque' object has no attribute 'method'
>>> insert_method = getattr(d, method)
>>> insert_method
<built-in method insert of collections.deque object at 0x000001E5638AC0>
>>> help(insert_method)
Help on built-in function insert:

insert(...) method of collections.deque instance
    D.insert(index, object) -- insert object before index

>>> insert_method(0, 1)
>>> d
deque([1])
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46