Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading