Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Python metaclasses different from regular class inheritance? [duplicate]

This might be too much of an open ended question, but I'm just now learning about metaclasses in Python and I don't understand how a metaclass is any different than just having a child class inherit from the parent class, like

class child(parent): 

Wouldn't this serve the same purpose of a metaclass? I guess maybe I don't understand the purpose of a metaclass.

like image 376
user2897013 Avatar asked Oct 19 '13 07:10

user2897013


People also ask

Are metaclasses inherited Python?

Principially, metaclasses are defined like any other Python class, but they are classes that inherit from "type". Another difference is, that a metaclass is called automatically, when the class statement using a metaclass ends.

Why would you use metaclasses?

A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass.

What are metaclasses and when are they used in Python?

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.

Does Python have metaprogramming?

The term metaprogramming refers to the potential for a program to have knowledge of or manipulate itself. Python supports a form of metaprogramming for classes called metaclasses. Metaclasses are an esoteric OOP concept, lurking behind virtually all Python code.


1 Answers

The difference is that inheriting from a class does not affect how the class is created, it only affects how instances of the class are created. If you do:

class A(object):     # stuff  class B(A):     # stuff 

then A does not have any opportunity to "hook in" when B is created. Methods of A may be called when an instance of B is created, but not when the class B itself is created.

Metaclasses allow you to define custom behavior for when a class is created. Refer to the question I marked as duplicate for examples of how metaclasses work, and convince yourself that there are effects in those examples that you can't achieve with normal inheritance.

like image 59
BrenBarn Avatar answered Oct 11 '22 13:10

BrenBarn