Saturday, 5 December 2015

Python: Get type of variable


You can get the type of a variable using ‘type()’ function or __class__ property.
>>> data=[1, 2, 3, 4]
>>> type(data)
<class 'list'>
>>> data.__class__
<class 'list'>
>>> 
>>> data={1:"hari", 2:"Krishna"}
>>> type(data)
<class 'dict'>
>>> data.__class__
<class 'dict'>

Checking the type using if statement
data={1:"hari", 2:"Krishna"}

#Approach 1
if(data.__class__.__name__ == 'dict' ):
    print("data is of type dictionary")
else:
    print("data is not dictionary type")

#Approach 2
if(type(data).__name__ == 'dict'):
    print("data is of type dictionary")
else:
    print("data is not dictionary type")

#Approach 3
if type(data)==type(dict()):
    print("data is of type dictionary")
else:
    print("data is not dictionary type")


Run above program, you will get following output.
data is of type dictionary
data is of type dictionary
data is of type dictionary

Check whether an object is instance of class or not
‘isinstance(object, classinfo)’ method is used to check whether an object is instance of given class or not. Return true if the object argument is an instance of the classinfo argument, or of a subclass thereof, else false.
data={1:"hari", 2:"Krishna"}

class Employee:
    def __init__(self, id, firstName, lastName):
     self.id = id
     self.firstName = firstName
     self.lastName = lastName

emp=Employee(1, "Hari", "Krishna")

print(isinstance(emp, Employee))
print(isinstance(emp, dict))
print(isinstance(data, dict))


Run above program, you will get following output.
True
False
True




Previous                                                 Next                                                 Home

No comments:

Post a Comment