Linked Questions

Popular Questions

Initialise class without instantiate?

Asked by At

I'm trying to work on a simple class that fills in some lists and then tries to retrieve that information back, something like:

class Foo(object):

    def __init__(self):
        self.src = []
        self.values = []

    def addItems(self, name, val):

    def getItem(self, item):
        for i, x in enumerate(self.src):
            if x == item:
                return self.src[i], self.values[i]

To use this class, I first have to instanciate it, Foo(), and only then start adding and retrieving objects.

a = Foo()
a.addItems('A', '1')
a.addItems('B', '2')
a.src  # ['A', 'B']
a.values  # ['1', '2']
a.getItem('A')  # ('A', '1')

Is there any way to add the elements without having to initialise the class first? Something like Foo.addItems('A', '1')(this gives a TypeError: addItems() missing 1 required positional argument: 'val').

I saw other related posts using @staticmethod, but couldn't figure out how to make it work in this example.

Related Questions