Reputation: 98
I have a list of namedtuples, for example:
[Student(ID='1', name='abc'), Room(number='1', location='4th floor'), Student(ID='2', name='xyz')]
While looping through this list, how do I check if an element is a Student or Room?
Upvotes: 0
Views: 266
Reputation: 24602
You can use isinstance
to check an object is an instance of a class.
>>> help(isinstance)
Help on built-in function isinstance in module builtins:
isinstance(obj, class_or_tuple, /)
Return whether an object is an instance of a class or of a subclass thereof.
A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
or ...`` etc.
>>>
>>> from collections import namedtuple
>>>
>>> Student = namedtuple('Student', ['ID', 'name'])
>>> Room = namedtuple('Room', ['location', 'floor'])
>>>
>>> obj = Student(ID=1, name='user')
>>> isinstance(obj, Student)
True
>>> isinstance(obj, Room)
False
If you are looking for class name you can get it by accessing obj.__class__.__name__
>>> obj = Student(ID=1, name='user')
>>> obj.__class__.__name__
'Student'
Upvotes: 1