Skip to main content
 首页 » 编程设计

python之从 parent 实例化 child

2025年05月04日19lidabo

是否可以在不具体传递子类名的情况下从父类实例化子类的实例?

在 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 类的实例,具体取决于调用它的对象。

或者这种方法太可怕了,不应该采用?

谢谢。

请您参考如下方法:

你不需要在 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>