Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a subscriptable class in Python (subscriptable class, not subscriptable object)?

Tags:

python

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.

like image 813
user805627 Avatar asked Jul 13 '12 10:07

user805627


People also ask

How do you fix an object is not Subscriptable in Python?

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.

What does it mean in Python when an object is not Subscriptable?

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.

Which object is Subscriptable?

In simple words, objects which can be subscripted are called sub scriptable objects. In Python, strings, lists, tuples, and dictionaries fall in subscriptable category.


1 Answers

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] 
like image 91
Luis Kleinwort Avatar answered Sep 29 '22 11:09

Luis Kleinwort