Is it possible to inheret a metaclass.
Peter Otten
__peter__ at web.de
Sat Apr 11 09:04:15 EDT 2020
Antoon Pardon wrote:
>
>
> Op 9/04/20 om 18:37 schreef Peter Otten:
>> Antoon Pardon wrote:
>>
>>> I am experimenting with subclasses that all need the same metaclass as
>>> the base class. Is there a way to make the metaclass be inherited, so
>>> that you don't have to repeat the "metaclass = MetaClass" with every
>>> subclass.
>>
>> ?
>>
>> This is not only possible, this is the default:
>>
>> >>> class Pardon(type): pass
>> ...
>>>>> class A(metaclass=Pardon): pass
>> ...
>>>>> class B(A): pass
>> ...
>>>>> type(B)
>> <class '__main__.Pardon'>
>
> Can you explain what is wrong with the code below:
>
> This produces only: Calling Pardon with A.
>
>
> def Pardon(cls, *args):
> print("Calling Pardon with", cls)
> return type(cls, *args)
>
> class A(metaclass=Pardon): pass
>
> class B(A): pass
As has been pointed out, the problem is the factory function you are using
instead of a class. One way to look at it:
class Foo:
pass
def make_foo():
return Foo()
foo = make_foo()
assert isinstance(foo, make_foo)
Would you expect the assertion to succeed? Would you expect that foo
remembers that it has been created by make_foo()?
No? Then replace the instance with the class, the class with the metaclass.
More information about the Python-list
mailing list