Python Program – Create class with Metaclass

CWC
3 Min Read

Python Program – Create a class with Metaclass

A metaclass in Python is a class of a class that defines how a class behaves. A class is itself an instance of a metaclass. A class in Python defines how the instance of the class will behave. In order to understand metaclasses well, one needs to have prior experience working with Python classes.

Metaclasses are the ‘stuff’ that creates classes.

if we have a variable having an integer value then its type is int. You can get the type of anything using the type() function.

The metaclass is responsible for the generation of classes, we need to write our custom metaclasses to modify the way classes are generated by performing extra actions or injecting code. In another way, we do not need custom metaclasses but sometimes it’s necessary.

class M(type):
pass

class A(object):
pass

class B(object):
__metaclass__ = M

a = A()
print(type(a))
b = B()
print(type(b))

 
class Meta(type):
def __init__(self, *args, **kwargs):
print('Meta.__init__')
print(self) # <class '__main__.C'>
print(args) # ('C', (<type 'object'>,),
# {'__module__': '__main__',
# '__metaclass__': <class '__main__.Meta'>})
print(kwargs) # {}

class C(object):
__metaclass__ = Meta
 
 c = C()
 print(type(c))
 
 class MyABC(type):
 def __init__(self, *args):
 print('Meta.__init__')
 print(args) # ('C', (<type 'object'>,),
 # {'__module__': '__main__',
 # '__metaclass__': <class '__main__.Meta'>})
 class Base(object):
 __metaclass__ = MyABC
  # Create a new-style class
  class A(object):
  pass
  print(type(A)) # <type 'type'>
  a = A()
  print(type(a)) # <class '__main__.A'>
  
 B = type('B', (), {})
 print(type(B)) # <type 'type'>
 b = B()
 print(type(b)) # <class '__main__.B'>
 
 # old style
 class C():
 pass
 print(type(C)) # <type 'classobj'>
 c = C()
 print(type(c)) # <type 'instance'>
 
 # Have attributes in the class
 class AA(object):
 name = 'Foo'
 print(AA.name) # Foo
 aa = AA()
 print(aa.name) # Foo
 
 BB = type('BB', (), {'name' : 'Bar'})
 print(BB.name) # Bar
 bb = BB()
 print(bb.name) # Bar
 
 # Intherit from a class
 class AAA(AA):
 pass
 print(AAA.name) # Foo
 aaa = AAA()
 print(aaa.name) # Foo
 
 BBB = type('BBB', (BB,), {})
 print(BB.name) # Bar
 bbb = BBB()
 print(bbb.name) # Bar
 
 def f(self):
 print(self.name)
 
 class AAAA(object):
 name = 'AAAA-Foo'
 def show(self):
 print(self.name)
 
 aaaa = AAAA()
 aaaa.show() # AAAA-Foo
 
 BBBB = type('BBBB', (), { 'name': 'BBBB-Bar', 'show' :
f})
 bbbb = BBBB()
 bbbb.show() # BBBB-Bar
Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version