How would i have a class return a list, tuple or dictionary?

Advertisements

I want to have a class return a list, tuple or dictionary.
And use it like a regular list

class MyClass:
  def __init__(self, *args):
    for i in range(len(args)):
      args[i] += 1
  
  def __some_dunder_method__(self):
    return self.args

obj = MyClass(0, 1, 2, 3, 4, 4)
print(obj[1]) # Wanted Output: 2
print(obj[2:5]) # Wanted Output: [3, 4, 5]


if 3 in obj: print("Yes")
else: print("No")
# Wanted Output: Yes

>Solution :

You do this with the __getitem__ and __setitem__ methods. This code just forwards those routines straight to the embedded list (which you forgot to create):

class MyClass:
  def __init__(self, *args):
    self.args = []
    for i in range(len(args)):
      self.args.append( args[i] + 1 )
  
  def __getitem__(self,n):
    return self.args.__getitem__(n)
  
  def __setitem__(self,n,k):
    return self.args.__setitem__(n,k)

obj = MyClass(0, 1, 2, 3, 4, 4)
print(obj[1]) # Wanted Output: 2
print(obj[2:5]) # Wanted Output: [3, 4, 5]

if 3 in obj: print("Yes")
else: print("No")
# Wanted Output: Yes

Output:

2
[3, 4, 5]
Yes

Alternatively, you can get the same effect just by deriving from the list type:

class MyClass(list):
  def __init__(self, *args):
    for i in range(len(args)):
      self.append( args[i] + 1 )

Same output.

Leave a ReplyCancel reply