Search code examples
pythonpython-3.xdryclass-method

Call a classmethod from __init__ without repeating the classname


I would like to call the classmethod addInstances from within __init__ without repeating the class name Foo.

class Foo():
    myInstances = {}

    @classmethod
    def addInstance(cls, name, obj):
        cls.myInstances[name]=obj

    def __init__(self, name):
        Foo.addInstance(name, self) # class name "Foo" is repeated

#use the class
if __name__ == "__main__":
    Foo('testName')
    print(Foo.myInstances)

The code above does what i expect it to do. However "Foo" is repeated.

Replacing the line

Foo.addInstance(name, self) # class name "Foo" is repeated

with

cls.addInstance(name, self)

leads to NameError: name 'cls' is not defined.


Solution

  • As long as you don't override addInstance as simple method

    self.addInstance 
    

    will work too.

    Both cls and self are conventions - unlike C++ this, which is standard.

    That's why you have to pass them explicitly - to classmethods and methods respectively

    You may also write

    self.__class__.addInstance