Example 1: class python
class MyClass(object):
def __init__(self, x):
self.x = x
Example 2: isistance exmaple
#Working of isinstance() with Native Types
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)
# Result
[1, 2, 3] instance of list? True
[1, 2, 3] instance of dict? False
[1, 2, 3] instance of dict or list? True
5 instance of list? False
5 instance of int? True
Example 3: isinstance python
isinstance(object, classinfo)
# if classinfo is a tuple of type objects (or recursively, other such tuples), return True
# if object is an instance of any of the types. If classinfo is not a type or tuple of types
# and such tuples, a TypeError exception is raised.
Example 4: instance method in python
# Instance Method Example in Python
class Student:
def __init__(self, a, b):
self.a = a
self.b = b
def avg(self):
return (self.a + self.b) / 2
s1 = Student(10, 20)
print( s1.avg() )
Example 5: how to check if a variable in python is a specific data type
isinstance(variable_name, class_name) #eg. isinstance(age, int) will return True
Example 6: isinstance python 3 not running
isinstance(object, classinfo)