Python subdirectory subclass in static method

It will be difficult to explain, but I'm trying to create a basic object to create other objects. The base class handles common tasks so that subclasses do not need to be implemented. However, I also need a static / class method that instantiates classes. So, for example, this is my base class:

class Base(object): def __init__(self, service, reference, vo=None): self.service = service self.reference = reference self.id = reference.getId() self.name = reference.getName() # do a database lookup here to get more information @staticmethod def get_objects(service, references, as_dict=False): """ More efficient way to get multiple objects at once. Requires the service instance and a list or tuple of references. """ vo_list = database.get_objects_from_references(references) items = list() for vo in vo_list: items.append(Base(service, vo.getRef(), vo)) return items 

The get_objects () method will take a list of identification numbers of records stored in the database, then get all these objects and make objects from them with one shot, and not hit the database for each identifier. The problem I am facing is that I have to use Base () in this method to instantiate the class. But this creates an instance of the Base class, not a subclass:

 class Something(Base): def __init__(self, service, reference, vo=None): Base.__init__(self, service, reference, vo) do_extra_stuff() 

My problem: I do not know if I can do this:

 Something.get_objects(service, references) 

Will it just run the Base init () method, or will it subclass the init () method (and the do_extra_stuff () method)?

+4
source share
1 answer

Instead, you want a class method that will receive the class object as its first parameter so that you can instantiate this particular class

 @classmethod def get_objects(cls, service, references, as_dict=False): """ More efficient way to get multiple objects at once. Requires the service instance and a list or tuple of references. """ vo_list = database.get_objects_from_references(references) items = list() for vo in vo_list: items.append(cls(service, vo.getRef(), vo)) return items 
+10
source

All Articles