To implement a subscriptable object is easy, just implement __getitem__
in this object's class definition.
But now I want to implement a subscriptable class. For example, I want to implement this code:
class Fruit(object): Apple = 0 Pear = 1 Banana = 2 #________________________________ #/ Some other definitions, \ #\ make class 'Fruit' subscriptable. / # -------------------------------- # \ ^__^ # \ (oo)\_______ # (__)\ )\/\ # ||----w | # || || print Fruit['Apple'], Fruit['Banana'] #Output: 0 2
I know getattr
can do the same thing, but I feel subscript accessing is more elegant.
The TypeError: 'int' object is not subscriptable error occurs if we try to index or slice the integer as if it is a subscriptable object like list, dict, or string objects. The issue can be resolved by removing any indexing or slicing to access the values of the integer object.
The “typeerror: 'int' object is not subscriptable” error is raised when you try to access an integer as if it were a subscriptable object, like a list or a dictionary. To solve this problem, make sure that you do not use slicing or indexing to access values in an integer.
In simple words, objects which can be subscripted are called sub scriptable objects. In Python, strings, lists, tuples, and dictionaries fall in subscriptable category.
Add something like this to your class:
class Fruit(object): def __init__(self): self.Fruits = {"Apple": 0, "Pear": 1, "Banana": 2} def __getitem__(self, item): return self.Fruits[item]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With