是否可以在不专门传递子类名的情况下从父类实例化子类的实例?
在 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 类的实例,具体取决于调用它的那个类。
还是这种方法太可怕了,不应该这样做?
谢谢。