Meta classes - real example

Ethan Furman ethan at stoneleaf.us
Tue Oct 18 10:42:16 EDT 2016


On 10/17/2016 11:44 PM, Mr. Wrobel wrote:

> Ok,so in general, we could say that using Metclasses is ok for manipulating __new__ but not that what is setting by __init__. Am I right?

No and yes.

In this code (python 2 syntax):

#untested
class Wonderful(object):

     __metaclass__ = SomeMetaClass
     
     diamond = Sparkly(7)
     club = 9

     def display(self):
         print "I'm an instance!"

The metaclass controls what happens when Wonderful is created:

- it can add the name 'diamond' to the Sparkly descriptor;
-  it can change/remove/add other attributes such as club, spade, or whatever;
- it can wrap methods such as display to pre- or post-process calls to it
- etc.

Once the class (Wonderful, in this example) has been created:

- x = Wonderful()  # metaclass not called
- x.display()      # metaclass not called
- x.diamond        # metaclass not called

- list(Wonderful)  # metaclass called (e.g. SomeMetaClass.__iter__(cls) )
                    # where cls = Wonderful


Check out http://stackoverflow.com/a/35730545/208880 for a simple demonstration of a metaclass.

--
~Ethan~



More information about the Python-list mailing list