我想获取班级中的班级列表。根据这个答案How to find all the subclasses of a class given its name?,我应该可以使用cls.__subclasses__
,但是此功能不存在。
我尝试了问题How to find all the subclasses of a class given its name?
的答案class X:
class my_subclass:
pass
x=X()
x.__subclassess__()
# This reports AttributeError 'X' has no attribute '__subclasses__'
我希望得到一个字典对象之类的东西。但是我只收到一条错误消息AttributeError 'X' has no attribute '__subclasses__'
。
答案 0 :(得分:2)
您做错了三件事。
1)那不是您创建子类的方式。
子类不是类 inside 中的类,而是一个单独的类,您可以从父类/基类定义 inherits 。参见Python: How do I make a subclass from a superclass?
class Cake():
pass
# a subclass of Cake
class Crepe(Cake):
pass
# a subclass of Cake
class Pound(Cake):
pass
2)您必须在父类名称而不是实例上调用__subclasses__
。
an_instance_of_crepe=Crepe()
an_instance_of_crepe.__subclasses__()
# This will result in "AttributeError: 'Crepe' object has no attribute '__subclasses__'"
# This is what you are getting
Cake.__subclasses__()
# This will work, and printing out the result will give
# [<class '__main__.Crepe'>, <class '__main__.Pound'>]
3)为__subclasses__
(末尾为1个“ s ”)
答案 1 :(得分:0)
方法的名称是
__subclasses__
您写道:
__subclassess__
看到多余的“ s”吗?