Course
Anonymous Class and Objects
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Anonymous Class and Objects
Python'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.Example
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))
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'>
The type() has a three argument version as follows
Syntax
newclass=type(name, bases, dict)
Using above syntax, a class can be dynamically created. Three arguments of type function are
name − name of the class which becomes __name__
attribute of new class
bases − tuple consisting of parent classes. Can be blank if not a derived class
dict − dictionary forming namespace of the new class containing attributes and methods and their values.
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
type of obj: <class '__main__.'>
Example
We can also add instance variables and instance methods dynamically. Take a look at this example
def getA(self): return self.aobj = type('',(object,),{'a':5,'b':6,'c':7,'getA':getA,'getB':lambda self : self.b})()print (obj.getA(), obj.getB())
It will produce the following output
5 6
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.