简体   繁体   English

python 元类冲突:除了父 class 之外,如何将附加参数传递给元 class

[英]python metaclass conflict : how to pass additional parameter to meta class apart from the parent class

This is my code snippet of trying to create a custom exception class which takes a input parameter about the exception这是我尝试创建自定义异常 class 的代码片段,它采用有关异常的输入参数

class Error(Exception):
    pass
mssg = "None"

class timepasserror(mssg ,Error):

    print(f"the error is {mssg}")
    

and I am planning to use it as mentioned below我打算如下所述使用它

if 1==1:#some conditon
    raise timepasserror('something')

I am getting this error:我收到此错误:

TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

I am not sure if its possible to do so.我不确定是否可以这样做。 If yes can anyone guide me Thanks如果是的话谁能指导我谢谢

You are having an error because you are trying something that does not make sense, trying to inherit from a string instance ( mssg = "None" ) - this will never work.你有一个错误,因为你正在尝试一些没有意义的东西,试图从一个字符串实例( mssg = "None" )继承 - 这永远不会工作。

Otherwise one will see this error (when trying to do things correctly) when trying to inherit from two classes which have differing metaclasses, and this question have been asked around plenty of times: the solution would be creating a base metaclass that inherits from both conflicting metaclasses - Abstract class inheriting from ABC and QMainWindow否则,当尝试从具有不同元类的两个继承时,会看到此错误(当尝试正确执行操作时),并且这个问题已经被问过很多次:解决方案是创建一个从两个相互冲突的类继承的基本元类元类 - 抽象 class 继承自 ABC 和 QMainWindow

In your case, please, take a step back and find out how to implement the behavior you want in your custom exception: it won't take multiple inheritance.在您的情况下,请退后一步,了解如何在自定义异常中实现您想要的行为:它不需要多个 inheritance。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM