JulianKarlBauer
JulianKarlBauer

Reputation: 287

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.

Upvotes: 1

Views: 1340

Answers (1)

volcano
volcano

Reputation: 3582

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

Upvotes: 1

Related Questions