Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Exploring Anonymous Classes and Objects in Python

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 −

Create an Anonymous Class

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, ), {})

Create an Anonymous 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__.'>

Anonymous Class and Object Example

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())

It will produce the following output −

5 6

Python

  1. Python File Management: Rename & Delete Files with Ease
  2. Master XML Parsing in Python: A Practical Guide Using Minidom and ElementTree
  3. Efficiently Measure Python Object Memory Usage with sys.getsizeof()
  4. Python list.count(): Expert Guide with Practical Examples
  5. How to Read and Write CSV Files in Python: A Comprehensive Guide
  6. Python Dictionary Fundamentals: Keys, Values, and Access
  7. Master Python Exception Handling: Using try, except, finally, and raise Effectively
  8. Hello World: Building Your First Python Application
  9. Master Python Exception Handling: A Comprehensive Guide
  10. Mastering Python Data Types: A Practical Guide