この記事では、について説明します。 type() および isinstance() 関数 パイソン 、との違いは何ですか? タイプ() そして インスタンス() 。
Pythonの型とは何ですか?
Python には type と呼ばれる組み込みメソッドがあり、これは通常、実行時にプログラムで使用される変数の型を把握するときに便利です。の 入力をチェックする標準的な方法 パイソン を以下に示します。
type() 関数の構文
type(object) type(name, bases, dict)>
例 1: 単一オブジェクトパラメータを使用した type() の例
この例では、各変数のデータ型を確認しようとしています。 x、s、y などを使用して type() 関数 。
Python3
# Python code type() with a single object parameter> x> => 5> s> => 'geeksforgeeks'> y> => [> 1> ,> 2> ,> 3> ]> print> (> type> (x))> print> (> type> (s))> print> (> type> (y))> |
階乗Java
>
>
出力:
class 'int' class 'str' class 'list'>
例 2: 名前、bases、および dict パラメーターを使用した type() の例
オブジェクトの型を確認する必要がある場合は、Python を使用することをお勧めします。 isinstance() 関数 その代わり。 isinstance() 関数は、指定されたオブジェクトがサブクラスのインスタンスであるかどうかもチェックするためです。
Python3
# Python code for type() with a name,> # bases and dict parameter> o1> => type> (> 'X'> , (> object> ,),> dict> (a> => 'Foo'> , b> => 12> ))> print> (> type> (o1))> print> (> vars> (o1))> class> test:> > a> => 'Foo'> b> => 12> o2> => type> (> 'Y'> , (test,),> dict> (a> => 'Foo'> , b> => 12> ))> print> (> type> (o2))> print> (> vars> (o2))> |
>
>
出力:
{'b': 12, 'a': 'Foo', '__dict__': , '__doc__': None, '__weakref__': } {'b': 12, 'a': 'Foo', '__doc__': None}>
Python の isinstance() とは何ですか?
isinstance() 関数は、オブジェクト (最初の引数) がクラス情報クラス (2 番目の引数) のインスタンスまたはサブクラスであるかどうかを確認します。
isinstance() 関数の構文
構文: インスタンス (オブジェクト、クラス情報)
パラメータ:
- object : チェック対象のオブジェクト
- classinfo : クラス、型、またはクラスと型のタプル
戻る: オブジェクトがクラスのインスタンスまたはサブクラスである場合は true、それ以外の場合は false。
クラス情報が型または型のタプルではない場合、TypeError 例外が発生します。
例 1:
この例では、クラス オブジェクトの test isinstance() が表示されます。
Python3
# Python code for isinstance()> class> Test:> > a> => 5> TestInstance> => Test()> print> (> isinstance> (TestInstance, Test))> print> (> isinstance> (TestInstance, (> list> ,> tuple> )))> print> (> isinstance> (TestInstance, (> list> ,> tuple> , Test)))> |
>
>
出力:
True False True>
例 2:
この例では、整数、浮動小数点数、および文字列オブジェクトに対する isinstance() のテストを示します。
Python3
weight> => isinstance> (> 17.9> ,> float> )> print> (> 'is a float:'> , weight)> num> => isinstance> (> 71> ,> int> )> print> (> 'is an integer:'> , num)> string> => isinstance> (> 'Geeksforgeeks'> ,> str> )> print> (> 'is a string:'> , string)> |
>
tostring メソッド
>
出力:
is a float: True is an integer: True is a string: True>
例 3:
この例では、 タプル 、リスト、 辞書 、 そして セット 物体。
Python3
tuple1> => isinstance> ((> 'A'> ,> 'B'> ,> 'C'> ),> tuple> )> print> (> 'is a tuple:'> , tuple1)> set1> => isinstance> ({> 'A'> ,> 'B'> ,> 'C'> },> set> )> print> (> 'is a set:'> , set1)> list1> => isinstance> ([> 'A'> ,> 'B'> ,> 'C'> ],> list> )> print> (> 'is a list:'> , list1)> dict1> => isinstance> ({> 'A'> :> '1'> ,> 'B'> :> '2'> ,> 'C'> :> '3'> },> dict> )> print> (> 'is a dict:'> , dict1)> |
>
>
出力:
is a tuple: True is a set: True is a list: True is a dict: True>
type() と isinstance() の違いは何ですか?
人々が犯す初歩的な間違いの 1 つは、isinstance() の方が適切なはずの type() 関数を使用することです。
- オブジェクトが特定の型であるかどうかを確認する場合は、最初の引数で渡されたオブジェクトが 2 番目の引数で渡された型オブジェクトのいずれかの型であるかどうかを確認するため、 isinstance() が必要になります。したがって、サブクラス化および古いスタイルのクラス (すべてがレガシー タイプのオブジェクト インスタンスを持つ) で期待どおりに動作します。
- 一方、 type() は単にオブジェクトの型オブジェクトを返します。返されたものを別の型オブジェクトと比較すると、両側でまったく同じ型オブジェクトを使用した場合にのみ True が得られます。 Python では、オブジェクトの型を検査するよりも、ダック タイピング (型チェックは実行時に延期され、動的型付けまたはリフレクションによって実装されます) を使用することをお勧めします。
Python3
# Python code to illustrate duck typing> class> User(> object> ):> > def> __init__(> self> , firstname):> > self> .firstname> => firstname> > @property> > def> name(> self> ):> > return> self> .firstname> class> Animal(> object> ):> > pass> class> Fox(Animal):> > name> => 'Fox'> class> Bear(Animal):> > name> => 'Bear'> # Use the .name attribute (or property) regardless of the type> for> a> in> [User(> 'Geeksforgeeks'> ), Fox(), Bear()]:> > print> (a.name)> |
スレッドの同期
>
>
出力:
Geeksforgeeks Fox Bear>
- 次に使わない理由は、 type() は継承をサポートしていません 。
Python3
# python code to illustrate the lack of> # support for inheritance in type()> class> MyDict(> dict> ):> > '''A normal dict, that is always created with an 'initial' key'''> > def> __init__(> self> ):> > self> [> 'initial'> ]> => 'some data'> d> => MyDict()> print> (> type> (d)> => => dict> )> print> (> type> (d)> => => MyDict)> d> => dict> ()> print> (> type> (d)> => => dict> )> print> (> type> (d)> => => MyDict)> |
>
>
出力:
False True True False>
- MyDict クラスには、新しいメソッドがなくても、辞書のすべてのプロパティが含まれています。辞書とまったく同じように動作します。ただし、type() は期待した結果を返しません。 isinstance() を使用することをお勧めします この場合、期待どおりの結果が得られるためです。
Python3
# python code to show isinstance() support> # inheritance> class> MyDict(> dict> ):> > '''A normal dict, that is always created with an 'initial' key'''> > def> __init__(> self> ):> > self> [> 'initial'> ]> => 'some data'> d> => MyDict()> print> (> isinstance> (d, MyDict))> print> (> isinstance> (d,> dict> ))> d> => dict> ()> print> (> isinstance> (d, MyDict))> print> (> isinstance> (d,> dict> ))> |
>
>
出力:
True True False True>