Python Anonymous Classes and Objects: Using the type() Function
Explore Python's type()
function to determine the class of an object. Learn how both built-in and user-defined classes are identified as objects of type class, with practical examples demonstrating its usage.
Python - Anonymous Class and Objects
Introduction
Python's type()
function returns the class that an object belongs to. Both built-in and user-defined classes are objects of type class.
Example
Here's an example demonstrating how to use type()
:
Example
class MyClass:
def __init__(self):
self.myvar = 10
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
class of int
class of list
class of dict
class of MyClass
class of obj
Creating an Anonymous Class
We can dynamically create a class using the three-argument version of the type()
function:
Syntax
newclass = type(name, bases, dict)
Arguments:
- name: Name of the class, becomes
__name__
attribute. - bases: Tuple of parent classes, can be empty if not a derived class.
- dict: Dictionary forming the namespace of the new class containing attributes and methods.
To create an anonymous class:
Example
anon = type('', (object,), {})
Creating an Anonymous Object
To create an object of the anonymous class:
Example
obj = anon()
print("type of obj:", type(obj))
Output
type of obj:
Adding Instance Variables and Methods Dynamically
We can add instance variables and methods to the anonymous class dynamically:
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
5 6