Table of Contents
TogglePython’s built-in type() function returns the class that an object belongs to. In Python, a class, both a built-in class or a user-defined class are objects of type class.
class myclass:
def __init__(self):
self.myvar=10
return
obj = myclass()
print ('class of int', type(int))
print ('class of list', type(list))
print ('class of dict', type(dict))
print ('class of myclass', type(myclass))
print ('class of obj', type(obj))
Output:
It will produce the following output −
class of int <class ‘type’>
class of list <class ‘type’>
class of dict <class ‘type’>
class of myclass <class ‘type’>
class of obj <class ‘__main__.myclass’>
The type() has a three argument version as follows −
newclass=type(name, bases, dict)
Using above syntax, a class can be dynamically created. Three arguments of type function are −
We can create an anonymous class with the above version of type() function. The name argument is a null string, second argument is a tuple of one class the object class (note that each class in Python is inherited from object class). We add certain instance variables as the third argument dictionary. We keep it empty for now.
anon=type('', (object, ), {})
To create an object of this anonymous class −
obj = anon()
print ("type of obj:", type(obj))
The result shows that the object is of anonymous class
Output:
type of obj: <class ‘__main__.’>
We can also add instance variables and instance methods dynamically. Take a look at this example −
def getA(self):
return self.a
obj = type('',(object,),{'a':5,'b':6,'c':7,'getA':getA,'getB':lambda self : self.b})()
print (obj.getA(), obj.getB())
Output:
It will produce the following output −
5 6
Key Takeaway: Master Python anonymous classes and objects—create dynamic types with type()—at Vista Academy!
