从父级实例化子级

时间:2012-10-27 21:36:41

标签: python

是否可以从父实例化实例化子类的实例而无需专门传递子类的名称?

在PHP中我可以做类似

的事情
$instance = new static;

如何在Python中实现类似的结果?

class DatabaseObject:
    @classmethod
    def findByID(caller, ID):
        query='SELECT * FROM {} LIMIT 1'.format(caller.tableName)
        #dostuff
        return Instance(stuff) #return the instance of the class that called this method

class Question(DatabaseObject):
    tableName='questions'

class Answer(DatabaseObject):
    tableName='answers'

q = Question.findByID(5)
a = Answer.findByID(5)

所以在这个例子中我想要的findByID方法返回的是Question类或Answer类的实例,具体取决于调用它的那个。

或者这种方法是否太可怕了,不应该这样做?

感谢。

2 个答案:

答案 0 :(得分:5)

你不需要在python中做任何特殊的事情。

class DatabaseObject:
    @classmethod
    def findByID(self, ID):
        # whatever
        return self()

class Question(DatabaseObject):
    tableName = 'questions'

class Answer(DatabaseObject):
    tableName = 'answers'

print Question.findByID(5) # <__main__.Question instance at 0x109b1d638>
print Answer.findByID(5) # <__main__.Answer instance at 0x109b1d638>

答案 1 :(得分:1)

由于提供给classmethod的第一个参数将是类本身,因此您可以返回cls(stuff)的实例:

class DatabaseObject:
    @classmethod
    def findByID(cls, ID):
        query='SELECT * FROM {} LIMIT 1'.format(caller.tableName)
        #dostuff
        return cls(stuff) #return the instance of the class that called this method

如果您只有一个类方法findByID,那么当然只需定义Question.__init__Answer.__init__就更直接了。但是,如果您还有其他类方法,比如findByExamfindByCourse等,那么我认为您将适当地使用类方法来进行实例化的其他途径。

相关问题