Pythonのでisinstance()

でisinstance()関数をチェックオブジェクト(最初の引数)がCLASSINFOクラス(第2引数)のインスタンスまたはサブクラスである場合。

でisinstanceの構文は()です:

isinstance(object, classinfo)

  

でisinstance()のパラメータ

 でisinstance()は、2つのパラメータを取ります。

  • オブジェクト  -  object チェックします
  • CLASSINFO  -クラス、タイプ、またはクラスと型のタプル

でisinstanceから値を返します()

でisinstance()が返されます:

  • True 場合  、オブジェクトは、  インスタンスまたはクラスのサブクラス、またはタプルの任意の要素であります
  • False さもないと

場合  CLASSINFOが  タイプや種類のタプルではない、  TypeError 例外が発生します。


例1:でisinstance()がどのように動作しますか?

class Foo:
  a = 5
  
fooInstance = Foo()

print(isinstance(fooInstance, Foo))
print(isinstance(fooInstance, (list, tuple)))
print(isinstance(fooInstance, (list, tuple, Foo)))


When you run the program, the output will be:

  

例2:ネイティブ型とでisinstanceのワーキング()

 

numbers = [1, 2, 3]

result = isinstance(numbers, list)
print(numbers,'instance of list?', result)

result = isinstance(numbers, dict)
print(numbers,'instance of dict?', result)

result = isinstance(numbers, (dict, list))
print(numbers,'instance of dict or list?', result)

number = 5

result = isinstance(number, list)
print(number,'instance of list?', result)

result = isinstance(number, int)
print(number,'instance of int?', result)


When you run the program, the output will be:
[1、2、3]リストのインスタンス?
辞書[1、2、3]インスタンス?
辞書やリストの[1、2、3]インスタンス?真の
リストの5インスタンス?
int型の5インスタンス?

 

ます。https://www.cnblogs.com/Xingtxx/p/11046070.htmlで再現

おすすめ

転載: blog.csdn.net/weixin_33816946/article/details/93224718