Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The direct answer to your question is: when you want to do <strong>more</strong> than just customize instance creation, or when you want to separate what the class <strong>does</strong> from how it's created.</p> <p>See my answer to <a href="https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python">Creating a singleton in Python</a> and the associated discussion.</p> <p>There are several advantages.</p> <ol> <li><p>It allows you to separate what the class <em>does</em> from the details of how it's created. The metaclass and class are each responsible for one thing.</p></li> <li><p>You can write the code once in a metaclass, and use it for customizing several classes' call behavior without worrying about multiple inheritance.</p></li> <li><p>Subclasses can override behavior in their <code>__new__</code> method, but <code>__call__</code> on a metaclass doesn't have to even call <code>__new__</code> at all.</p></li> <li><p>If there is setup work, you can do it in the <code>__new__</code> method of the metaclass, and it only happens once, instead of every time the class is called. </p></li> </ol> <p>There are certainly lots of cases where customizing <code>__new__</code> works just as well if you're not worried about the single responsibility principle.</p> <p>But there are other use cases that have to happen earlier, when the class is created, rather than when the instance is created. It's when these come in to play that a metaclass is necessary. See <a href="https://stackoverflow.com/questions/392160/what-are-your-concrete-use-cases-for-metaclasses-in-python">What are your (concrete) use-cases for metaclasses in Python?</a> for lots of great examples.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload