How to call classmethod of base class from derived class when base class itself is inheriting from another library class (ndb.Model)

63 views Asked by At

I know questions related to classmethods in python have been answered many times, but even after implementing those solutions, the problem I'm facing still persists.

I came across many answers which really helped me understand the base logic but due to the ndb.Model implementation here, I'm finding it hard to pinpoint the issue.

My code structure,

class A(ndb.Model):
    @classmethod
    def fun(cls, input):
        db_obj = cls.get_by_id(input) # get_by_id is ndb.Model function that brings record from db
        return db_obj.required_data 

class B(A):
    @classmethod
    def fun(cls, input):
        required_data = super(B, cls).fun(input)

When we reach to cls.get_by_id(input), nothing is returned from DB even when the required record is present. When I don't make the derived class fun() as classmethod and call it directly like A.fun(), it then works. But, this would not be the correct implementation I believe.

Any help with the above would be great. Thank you!

1

There are 1 answers

1
minou On

Is the datastore entity that you are trying to retrieve an A entity or a B entity?

I suspect it is a B entity since you are starting the process with B.fun().

If that is the case, then the get_by_id in A.fun() won't work because it is trying to retrieve an A entity. The cls in A.fun() is A and not B and thus it is trying to get an A entity that doesn't exist.

A solution could be to modify A.fun to also take a parameter that indicates the type of entity to retrieve. This could be the class or just a string. Something like this:

class A(ndb.Model):
    @classmethod
    def fun(cls, input, cls2):
        db_obj = cls2.get_by_id(input) # get_by_id is ndb.Model function that brings record from db
        return db_obj.required_data 

class B(A):
    @classmethod
    def fun(cls, input):
        required_data = super(B, cls).fun(input, cls)