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

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

クラスメソッドが 1 つしかない場合はfindByID、当然、Question.__init__andを定義する方がより直接的Answer.__init__です。しかしfindByExamfindByCourse、 などの他のクラスメソッドもある場合は、クラスメソッドを適切に使用して、インスタンス化のための他の手段を作成していると思います。

于 2012-10-27T21:39:47.780 に答える