This is what 99% Pythonistas might not know !

Creating a Class factory !
assembly_line.gif (480×270) (biol355.github.io)

Meta-Class

class my_class(metaclass=type):
pass

Come, Lets check type of classes in Python!

for i in int, float, dict, list, tuple:
print(type(i))
OUTPUT<class 'type'>
<class 'type'>
<class 'type'>
<class 'type'>
<class 'type'>
class A:
pass
print(type(a))
OUTPUT<class 'type'>
print(type(type))OUTPUT<class 'type'>

Creating a class using Type function

Type function syntax to define a classtype(name, bases, dict)name: Required. A class name.bases: Required. A tuple that itemizes the base class.dict: Required. A dictionary which is the namespace containing definitions for the class body.

Lets, write an empty class using Type Function

#Creating an empty class using Type function My_class_var = type(‘My_class’, (), {})
#Normal way to create an empty classclass My_normal_class:
pass

Now, lets add some functions in the class

# Creating class with an attribute using Type functiondef fun(obj):
print("Learning Metaclass")
My_class_var = type('My_class', (object,), {
'attr1' : 100,
'attr2':lambda x : x.attr1

'attr3' : fun
})My_class_obj = My_class_var()
print(My_class_obj.attr1)
print(My_class_obj.attr2())
print(My_class_obj.attr3())
OUTPUT100
100
Learning Metaclass

Why Meta Class ?

Tim Peters, Author of Zen of Python explains meta class like below

Creating a custom Meta-Class

# Creating our Meta Classclass My_Class_factory(type):  def __new__(cls, name, bases, dct):     x = super().__new__(cls, name, bases, dct)     x.name = “Asd”     x.age=123     return x
# Creating first class using this custom meta class class Class1(metaclass=My_Class_factory): passobj1= Class1()print(obj1.name)
# Creating second class using this custom meta classclass Class2(metaclass=My_Class_factory): passobj2= Class2()print(obj2.name)
# Creating third class using this custom meta classclass Class3(metaclass=My_Class_factory): passobj3= Class3()print(obj3.name)OUTPUTAsd
Asd
Asd

--

--

Adventures-of-a-Programmer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store