Python type()没有给出确切的类类型,而是给出了元类类型

2024-06-26 00:04:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将类的类型传递给一个方法,以便可以动态地实例化它。该类扩展到基类,基类进一步扩展到抽象类。现在,当我检查类的类型时,它是抽象类类型,而不是子类。你知道吗

我的课是这样的

class AMeta(type):
     # stuff

class Parent(six.with_metaclass(AMeta, object)):
     # stuff

class Child(Parent):
    # stuff

现在当我使用type(Child) or Child.__class__时,它会给我AMeta,而我希望得到Child。我想把这个子对象传递给另一个方法,这个方法将动态地创建它的对象。你知道吗

def create_obj(clzz):
   return clzz()

当我调用像create_obj(type(Child))这样的方法时,它不工作并且会中断,但是当我调用Child.mro()[0]时,它工作得很好这里正在发生的事情,有没有其他方法来实现我通过mro方法实现的目标?你知道吗


Tags: 对象方法childobj类型typecreate抽象类
2条回答

如果你做了type(Child),你会问你的Child类的type是什么。请记住,类在Python中也是实例。在脚本中执行class Child...时,会向脚本的命名空间添加一个新名称(Child)(实际上是一个名为Child的变量,类型为AMeta,因为您指定AMetaChild的元类。否则,它将是type类型,有点像“default”元类)

请参见:

import six

class AMeta(type):
     pass

class Parent(six.with_metaclass(AMeta, object)):
     pass

class Child(Parent):
    pass

print(type(Child))
c=Child()
print(type(c))

在第一次打印中,您得到<class '__main__.AMeta'>,因为您要问我的孩子实例的类型是什么?。在第二次打印中,你会得到<class '__main__.Child'>,因为你在问我的c实例的类型是什么?

无需执行type(Child)即可获得类。你可以直接用。例如:

obj = Child
dynamic_instance = obj()
print(type(dynamic_instance))

将打印<class '__main__.Child'>

更接近你的例子是:

def create_obj(clzz):
   return clzz()

a = create_obj(Child)
print("Just created: %s" % type(a))

输出Just created: <class '__main__.Child'>

类是其元类的实例。因此:

  • Child的类型是AMeta
  • 一个Child()的类型是Child

相关问题 更多 >