Is there something like typeof in Python?

4

As the title says, is there a way to get the internal data type of a variable in Python 3?

In C # I can compare it in the following way:

var str = "Strings";

if (str.GetType() == typeof(string))
    Debug.WriteLine("str es un string.");

But I can not find a way to do it in python.

    
asked by NaCl 01.07.2016 в 18:19
source

2 answers

3

Yes, instead of typeof is type :

>>> type("hola mundo")
<type 'str'>
>>> type(6)
<type 'int'>
>>> 

Edit: In python 3 it returns class instead of type but I guess that does not affect in this case:

>>> type("hola mundo")
<class 'str'>
>>> type(6)
<class 'int'>
>>> type([1,2])
<class 'list'>
    
answered by 01.07.2016 / 18:28
source
2

As in C #, python talks about types and classes interchangeably. The difference is in python there is multiple inheritance and asking about the type of an object is somewhat ambiguous.

The correct way to check the type of an object is to use isinstance (equivalent to is of C #):

>>> isinstance(s, str)
true
    
answered by 02.07.2016 в 18:45