ここでは、2 つの関数について簡単に説明します。この演習を通して、私はそれが明るくなったと感じました。私はよく、単純な関数の内外を調査する単純なプログラムを作成し、参照用に保存します。
#
# Testing isinstance and issubclass
#
class C1(object):
def __init__(self):
object.__init__(self)
class B1(object):
def __init__(self):
object.__init__(self)
class B2(B1):
def __init__(self):
B1.__init__(self)
class CB1(C1,B1):
def __init__(self):
# not sure about this for multiple inheritance
C1.__init__(self)
B1.__init__(self)
c1 = C1()
b1 = B1()
cb1 = CB1()
def checkInstanceType(c, t):
if isinstance(c, t):
print c, "is of type", t
else:
print c, "is NOT of type", t
def checkSubclassType(c, t):
if issubclass(c, t):
print c, "is a subclass of type", t
else:
print c, "is NOT a subclass of type", t
print "comparing isinstance and issubclass"
print ""
# checking isinstance
print "checking isinstance"
# can check instance against type
checkInstanceType(c1, C1)
checkInstanceType(c1, B1)
checkInstanceType(c1, object)
# can check type against type
checkInstanceType(C1, object)
checkInstanceType(B1, object)
# cannot check instance against instance
try:
checkInstanceType(c1, b1)
except Exception, e:
print "failed to check instance against instance", e
print ""
# checking issubclass
print "checking issubclass"
# cannot check instance against type
try:
checkSubclassType(c1, C1)
except Exception, e:
print "failed to check instance against type", e
# can check type against type
checkSubclassType(C1, C1)
checkSubclassType(B1, C1)
checkSubclassType(CB1, C1)
checkSubclassType(CB1, B1)
# cannot check type against instance
try:
checkSubclassType(C1, c1)
except Exception, e:
print "failed to check type against instance", e
編集:
isinstance は API 実装を壊す可能性があるため、次のことも考慮してください。例としては、辞書のように機能するオブジェクトですが、dict から派生したものではありません。isinstance は、オブジェクトがディクショナリ スタイルのアクセスをサポートしている場合でも、オブジェクトがディクショナリであることを確認する場合があります:
isinstance は有害と見なされます
編集2:
Type を 2 番目の引数として渡す場合と Object を渡す場合の違いの例を教えてください。
上記のコードをテストすると、2 番目のパラメーターは型でなければならないことがわかります。したがって、次の場合:
checkInstanceType(c1, b1)
呼び出しは失敗します。次のように記述できます。
checkInstanceType(c1, type(b1))
したがって、あるインスタンスのタイプを別のインスタンスと比較してチェックしたい場合は、type() 組み込み呼び出しを使用する必要があります。