我正在调试一个 Python 脚本(Python 并不是我首选的语言),这是我第一次在 Python 中使用元类。当我按照下面的代码运行时,我遇到了元类冲突错误。
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
在尝试解决它时,我将 MySQLMSoftware
中的元类声明注释掉了,认为这是多余的,因为它继承自具有相同元类声明的类,但这会导致:
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)
任何见解、指导或方向都将不胜感激。我一直在阅读有关Python元类实现的文章,但至今仍未找到问题所在。 MSoftware.py
from abc import ABCMeta, abstractmethod
class MSoftware(object) :
__metaclass__ = ABCMeta
def __init__(self,name,spark=None,mysql=None):
self.name = name
...
MySQLMSoftware.py
from mouse import Mouse, MSoftware
from abc import ABCMeta, abstractmethod
class MySQLMSoftware(MSoftware): # Traceback always goes here
__metaclass__ = ABCMeta
MAX_ROWS = 30000000
def __init__(self,name,years,spark=None,mysql=None):
MSoftware.__init__(self,name,spark,mysql)
self.years = years
...
TTime.py
from mouse.Mouse import Mouse
from mouse.MySQLMSoftware import MySQLMSoftware
class TTime(MySQLMSoftware) :
DATABASE = "Database"
NAME = "table"
YEARS = [2014,2016]
def __init__(self,spark=None,mysql=None):
MySQLMSoftware.__init__(self,TTime.NAME,TTime.YEARS,spark,mysql)
...
main.py
import sys
from mouse.Mouse import Mouse
from mouse.TTime import TTime
...
MSoftware
似乎有一个元类(不是ABCMeta
)——这是真的吗?如果是这样,你可以尝试使用__metaclass__ = type('MySQLMSoftware', (type(MSoftware), ABCMeta), {})
。但我没有这些类来测试,所以不能保证它会起作用... - mgilson__metaclass__
语法在Python3.x中有所改变,而在Python3.x中,在类上设置__metaclass__
属性不会出现错误。 - mgilsonMSoftware.py
文件中显示了一个MSoftware
类,但是你的其他文件(发生异常的文件)继承自mouse
模块中定义的MSoftware
类,而不是MSoftware
模块。你能找到并展示mouse.py
吗?也许mouse.MSoftware
和MSoftware.MSoftware
不是同一个东西。 - Blckknght