2014-03-31 131 views
0

我相信这个问题听起来有点令人困惑,所以我会在下面给出更多细节。在创建类时动态分配一个动态创建的元类

我有这两个类定义,其中一个继承type:现在

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


class Product(object): 
    __metaclass__ = ProductType 

,在运行时,我创建的ProductType一个子类:

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

,然后创建一个子类Product,将其元类设置为Insurance

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

现在,由于一些明显的原因(我现在看不出来),如果我做type(HouseInsurance)我得到ProductType,而不是Insurance。看起来动态创建的类由于某种原因忽略了给定的动态创建的元类。为什么会发生这种情况,我该如何解决这个问题?

回答

2

相反,使用

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

__metaclass__是一个程序员来表达一个类对象的文件解析时间的构造,而不是运行时的方式。

+0

哦,我知道这会很简单。感谢您指出这一点! – linkyndy