Question

I believe the question sounds a bit confusing, so I'll give more details in the following.

I have these two classes define, one of which inherits type:

class ProductType(type):
    def __new__(cls, name, bases, attrs):
        return super(ProductType, cls).__new__(cls, name, bases, attrs)


class Product(object):
    __metaclass__ = ProductType

Now, at runtime, I create a subclass of ProductType:

Insurance = type('Insurance', (ProductType,), {})

And then, create a subclass of Product, which will have it's metaclass set as Insurance:

HouseInsurance = type('HouseInsurance', (Product,), {'__metaclass__': Insurance})

Now, for some obvious reason (which I don't seem to see by now), if I do type(HouseInsurance) I get ProductType, not Insurance. It seems that the dynamically created class ignores the given dynamically created metaclass for some reason. Why is this happening and how can I fix this?

Was it helpful?

Solution

Instead, use

>>> HouseInsurance = Insurance('HouseInsurance', (Product,), {})
>>> type(HouseInsurance)
__main__.Insurance

__metaclass__ is a way for a programmer to express the constructor of a class object at file parsing time, as opposed to runtime.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top