0

これに似たコードをいくつか取得しました。正確ではありませんが、あまり言いませんが、check_typeがr_typeパラメータを文字列として受け入れ、オブジェクト タイプがこの文字列の値であるかどうかを確認する必要があります。それは実行可能ですか?!?!?

繰り返しますが、それはできません: n.check_type(r_type=Newer)* 、構成ファイルからr_type値を取得する必要があり、その方法は文字列です!

    class New(object):
        def check_type(self, r_type):
            print 'is instance of r_type: ', isinstance(self, r_type)
            return isinstance(self, r_type)

    class Newer(New):
        pass

    if __name__ == '__main__':
        n = Newer()
        n.check_type(r_type='Newer')

出力:

        print 'is instance of r_type: ', isinstance(self, r_type)
    TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
4

2 に答える 2

3

グローバル辞書を使用して実際のクラスをその名前で取得し、それを使用して isinstance で確認できます

>>> class New(object):
        def check_type(self,r_type):
            result = isinstance(self,globals()[r_type])
            print "is instance of r_type: ",result
            return result


>>> class Newer(New):
        pass

>>> n=Newer()
>>> n.check_type("Newer")
is instance of r_type:  True
True
>>> 
于 2016-02-17T11:50:35.857 に答える