1

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

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

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

谢谢。

4

2 回答 2

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>
于 2012-10-27T21:45:15.953 回答
1

由于提供给类方法的第一个参数将是类本身,因此您可以返回一个实例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__and会更直接Answer.__init__。但是,如果您还有其他类方法,例如findByExam,findByCourse等,那么我认为您将适当地使用类方法来为实例化提供其他途径。

于 2012-10-27T21:39:47.780 回答