Is there a more pythonic way to write __getitem__ than the following? The issue is checking type and doing different things depending on the type of the parameter in the call.
class This():
def __init__(self, name, value):
self.name, self.value = name, value
class That():
def __init__(self):
self.this_list = []
def add_this(self, this):
self.this_list.append(this)
def __getitem__(self, x):
if isinstance(x, int):
return self.this_list[x] # could wrap in try/except for error checking
elif isinstance(x, str):
for this in self.this_list:
if this.name == x:
return this
return None
a = This('a', 1)
b = This('b', 2)
c = That()
c.add_this(a)
c.add_this(b)
print c[1].name
print c['a'].name
There are quite a few options, but I think there is not one best choice. It depends on your use case and preferences. Just to give you a few hints:
Do you really have to store the data in a list? In your example you could use a dictionary and insert the object twice: Once using the integer as key and once using the string as a key. That would make your
__getitem__quite simple. 😉Another option would be to make your interface more explicit and use
byInt/byStringmethods. You should choose better names of course.If you give more details about what you really want to do, I could propose more alternatives.