masonjarre
masonjarre

Reputation: 891

Constructing from a classmethod

Suppose I am creating a class representing and object in a KV-datastore. Creating the constructor is pretty straightforward...

class KVObject:
    def __init__(self, key, value, add=True):
        self.key = key
        self.value = value
        if add == True:
            kv_create(key, value)

Now, let's say I want to retrieve a KV-object... and construct a class instance from it. I figure I'll add this class method onto my DataBaseObject class.

     @classmethod
     def get_kv_object(cls, key):
         value = kv_get(key)
         cls.__init__(key, value, add=False)

... but when calling init from the class method (cls.__init__), Python asks for an argument for self!

Any ideas? Many thanks! I know this is a bit of a simple example, but it definitely applies to some more complex, interesting situations!

Edit: Thanks for the responses. I learned something helpful while researching this, which is that object.__new__ calls __init__ on an object when calling MyClass(...), effectively providing an uninitialized instance of the class to MyClass.init with the args called from within MyClass. Likewise, it makes sense to call cls(...), as suggested in your answers. Thank you.

Upvotes: 0

Views: 151

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208455

Think about how you would create a new database object normally, it would be something like the following:

instance = DatabaseObject(key, value, add=False)

Well within your class method the first parameter (cls in this case) is just another name for DatabaseObject, so to create an instance you would do the following:

instance = cls(key, value, add=False)

Upvotes: 2

Maciej Gol
Maciej Gol

Reputation: 15854

@classmethod
 def get_kv_object(cls, key):
     value = kv_get(key)
     return cls(key, value, add=False)

__init__ does not created new instances of the cls class! It's a method that's called right after the object has been created.

Upvotes: 1

Related Questions