1966

変数の型が符号なし 32 ビットか符号付き 16 ビットかなどを確認するにはどうすればよいですか?

どうすれば表示できますか?

4

19 に答える 19

1817

type()組み込み関数を使用します。

>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True

変数が特定の型であるかどうかを確認するには、次を使用しますisinstance

>>> i = 123
>>> isinstance(i, int)
True
>>> isinstance(i, (float, str, set, dict))
False

Python には C/C++ と同じ型がないことに注意してください。これが質問のようです。

于 2008-12-31T10:43:07.240 に答える
505

組み込み関数を探している可能性があります。type()

以下の例を参照してください。ただし、Python には Java のような「符号なし」型はありません。

正の整数:

>>> v = 10
>>> type(v)
<type 'int'>

大きな正の整数:

>>> v = 100000000000000
>>> type(v)
<type 'long'>

負の整数:

>>> v = -10
>>> type(v)
<type 'int'>

文字のリテラル シーケンス:

>>> v = 'hi'
>>> type(v)
<type 'str'>

浮動小数点整数:

>>> v = 3.14159
>>> type(v)
<type 'float'>
于 2008-12-31T08:02:04.660 に答える
201

とてもシンプルです。このようにします。

print(type(variable_name))
于 2015-10-01T11:02:32.097 に答える
143

How to determine the variable type in Python?

So if you have a variable, for example:

one = 1

You want to know its type?

There are right ways and wrong ways to do just about everything in Python. Here's the right way:

Use type

>>> type(one)
<type 'int'>

You can use the __name__ attribute to get the name of the object. (This is one of the few special attributes that you need to use the __dunder__ name to get to - there's not even a method for it in the inspect module.)

>>> type(one).__name__
'int'

Don't use __class__

In Python, names that start with underscores are semantically not a part of the public API, and it's a best practice for users to avoid using them. (Except when absolutely necessary.)

Since type gives us the class of the object, we should avoid getting this directly. :

>>> one.__class__

This is usually the first idea people have when accessing the type of an object in a method - they're already looking for attributes, so type seems weird. For example:

class Foo(object):
    def foo(self):
        self.__class__

Don't. Instead, do type(self):

class Foo(object):
    def foo(self):
        type(self)

Implementation details of ints and floats

How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?

In Python, these specifics are implementation details. So, in general, we don't usually worry about this in Python. However, to sate your curiosity...

In Python 2, int is usually a signed integer equal to the implementation's word width (limited by the system). It's usually implemented as a long in C. When integers get bigger than this, we usually convert them to Python longs (with unlimited precision, not to be confused with C longs).

For example, in a 32 bit Python 2, we can deduce that int is a signed 32 bit integer:

>>> import sys

>>> format(sys.maxint, '032b')
'01111111111111111111111111111111'
>>> format(-sys.maxint - 1, '032b') # minimum value, see docs.
'-10000000000000000000000000000000'

In Python 3, the old int goes away, and we just use (Python's) long as int, which has unlimited precision.

We can also get some information about Python's floats, which are usually implemented as a double in C:

>>> sys.float_info
sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, 
min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, 
mant_dig=53, epsilon=2.2204460492503131e-16, radix=2, rounds=1)

Conclusion

Don't use __class__, a semantically nonpublic API, to get the type of a variable. Use type instead.

And don't worry too much about the implementation details of Python. I've not had to deal with issues around this myself. You probably won't either, and if you really do, you should know enough not to be looking to this answer for what to do.

于 2016-10-07T16:02:24.543 に答える
73
print type(variable_name)

このような質問に対処するときは、 IPythonインタラクティブ インタープリターも強くお勧めします。variable_name?入力すると、タイプとそのタイプのドキュメント文字列を含む、オブジェクトに関する情報の完全なリストが返されます。

例えば

In [9]: var = 123

In [10]: var?
Type:       int
Base Class: <type 'int'>
String Form:    123
Namespace:  Interactive
Docstring:
    int(x[, base]) -> integer

可能であれば、文字列または数値を整数に変換します。浮動小数点引数はゼロに向かって切り捨てられます (これには、浮動小数点数の文字列表現は含まれません!) 文字列を変換するときは、オプションの base を使用します。非文字列を変換するときに基数を指定するとエラーになります。引数が整数の範囲外の場合、代わりに long オブジェクトが返されます。

于 2008-12-31T08:02:11.493 に答える
57
a = "cool"
type(a)

//result 'str'
<class 'str'>
or 
do 
`dir(a)` 
to see the list of inbuilt methods you can have on the variable.
于 2019-03-09T10:30:20.423 に答える
41

を使用するもう1つの方法__class__

>>> a = [1, 2, 3, 4]
>>> a.__class__
<type 'list'>
>>> b = {'key1': 'val1'}
>>> b.__class__
<type 'dict'>
>>> c = 12
>>> c.__class__
<type 'int'>
于 2015-03-18T02:48:04.200 に答える
25

質問はややあいまいです-「ビュー」の意味がわかりません。ネイティブの Python オブジェクトの型を照会しようとしている場合は、 @atzzの回答が正しい方向に導きます。

ただし、プリミティブ C 型 ( 、 など) のセマンティクスを持つ Python オブジェクトを生成しようとしている場合は、モジュール使用してください。次のようにして、特定の C 型プリミティブのビット数を決定できます。uint32_tint16_tstruct

>>> struct.calcsize('c') # char
1
>>> struct.calcsize('h') # short
2
>>> struct.calcsize('i') # int
4
>>> struct.calcsize('l') # long
4

これはarrayモジュールにも反映されており、これらの下位レベルの型の配列を作成できます。

>>> array.array('c').itemsize # char
1

サポートされている最大整数 (Python 2 のint) はsys.maxintで指定されます。

>>> import sys, math
>>> math.ceil(math.log(sys.maxint, 2)) + 1 # Signedness
32.0

sys.getsizeofもあります。これは、 Pythonオブジェクトの実際のサイズを残りのメモリに返します。

>>> a = 5
>>> sys.getsizeof(a) # Residual memory.
12

float データと精度データの場合は、sys.float_infoを使用します。

>>> sys.float_info
sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.2204460492503131e-16, radix=2, rounds=1)
于 2008-12-31T08:08:06.693 に答える
23

Pythonで意味していますか、それともctypesを使用していますか?

最初のケースでは、Python には符号付き/符号なしの 16/32 ビット整数がないため、単純にできません。

2 番目のケースでは、以下を使用できますtype()

>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>

そのタイプである ctypes の詳細については、公式ドキュメントを参照してください。

于 2008-12-31T08:10:54.817 に答える
17

Python には、あなたが説明したような型はありません。整数値を表すために使用される 2 つの型があります: intC のプラットフォームの int 型に対応する とlong、任意精度の整数 (つまり、必要に応じて大きくなり、上限がない) です。式が に格納できない結果を生成する場合、intは黙って に変換されます。longint

于 2008-12-31T08:12:34.593 に答える
12

それは本当にあなたが意味するレベルに依存します。Python 2.xには、歴史的な理由から、 int(に制約されたsys.maxint)と(無制限の精度)の2つの整数型があります。longPythonコードでは、数値が大きすぎるとインタプリタが自動的にlongに変換されるため、これによる違いはほとんどありません。基礎となるインタープリターで使用される実際のデータ型について知りたい場合は、実装によって異なります。(CPythonはObjects/intobject.cおよびObjects/longobject.cにあります。)システムタイプについては、structモジュールを使用するためのcdlearyanswerを参照してください。

于 2008-12-31T14:36:51.540 に答える
1

Python は動的型付け言語です。最初に文字列として作成された変数は、後で整数または浮動小数に再割り当てできます。そして通訳者は文句を言いません:

name = "AnyValue"
# Dynamically typed language lets you do this:
name = 21
name = None
name = Exception()

変数の型を確認するには、組み込み関数type()またはisinstance()を使用できます。それらを実際に見てみましょう:

Python3 の例:

variable = "hello_world"
print(type(variable) is str) # True
print(isinstance(variable, str)) # True

performancespython3 で両方の方法を比較してみましょう

python3 -m timeit -s "variable = 'hello_world'" "type(variable) is int"
5000000 loops, best of 5: 54.5 nsec per loop

python3 -m timeit -s "variable = 'hello_world'" "isinstance(variable, str)"
10000000 loops, best of 5: 39.2 nsec per loop

type は約 40% 遅くなります (54.5/39.2 = 1.390)。

代わりに使用できますtype(variable) == str。それはうまくいくでしょうが、それは悪い考えです:

  • ==変数の値を確認したいときに使用する必要があります。これを使用して、変数の値が「hello_world」と等しいかどうかを確認します。しかし、変数が文字列かどうかを確認したい場合は、 is 演算子の方が適切です。どちらを使用するかについての詳細な説明については、この記事を参照してください。
  • ==遅いです:python3 -m timeit -s "variable = 'hello_world'" "type(variable) == str" 5000000 loops, best of 5: 64.4 nsec per loop

インスタンスとタイプの違い

これら 2 つの機能の違いは速度だけではありません。実際には、それらがどのように機能するかの間には重要な違いがあります。

  • type は、オブジェクトのタイプ (クラス) のみを返します。これを使用して、変数が str 型かどうかを確認できます。
  • isinstance指定されたオブジェクト (最初のパラメーター) が以下であるかどうかを確認します。
    • 2 番目のパラメーターとして指定されたクラスのインスタンス。たとえば、変数は str クラスのインスタンスですか?
    • または、2 番目のパラメーターとして指定されたクラスのサブクラスのインスタンス。つまり、変数は str のサブクラスのインスタンスですか?

実際にはどういう意味ですか?リストとして機能するが、いくつかの追加メソッドを持つカスタム クラスが必要だとしましょう。したがって、リスト型をサブクラス化し、内部にカスタム関数を追加することができます:

class MyAwesomeList(list):
    # Add additional functions here
    pass

しかし、この新しいクラスをリストと比較すると、type と isinstance は異なる結果を返すようになりました!

my_list = MyAwesomeList()
print(type(my_list) is list) # False
print(isinstance(my_list, list)) # True

isinstancemy_listは がリストのインスタンスであるか (そうではない)、またはリストのサブクラスであるか (リストのサブクラスであるため) をチェックするため、異なる結果が得られますMyAwesomeList。この違いを忘れると、コードに微妙なバグが発生する可能性があります。

結論

isinstance通常、タイプを比較するための推奨される方法です。高速であるだけでなく、多くの場合、望ましい動作である継承も考慮されています。Python では、通常、特定のオブジェクトが文字列またはリストのように動作するかどうかを確認する必要がありますが、それが正確に文字列であるかどうかは必ずしも必要ではありません。したがって、文字列とそのすべてのカスタム サブクラスをチェックする代わりに、isinstance を使用できます。

一方、特定の変数が特定の型 (およびそのサブクラスではない) であることを明示的に確認する場合は、 を使用しますtype。そして、それを使用するときは、次のように使用します:type(var) is some_typeではなく、次のように使用しますtype(var) == some_type

于 2022-03-01T18:56:22.830 に答える