我和一大班同学一起做一个项目。最初,它们被实现为只需导入的函数,如in this answer:
def plot(self, x, y):
print(self.field)
def clear(self):
# body
@classmethod
def from_file(cls, path):
# body
class Fitter(object):
def __init__(self, whatever):
self.field = whatever
# Imported methods
from .some_file import plot, clear, from_file
...
但我认为这不是最好的解决方案,IDE对代码非常着迷,因为它无法在外部方法中找到field
,并且认为某些函数上的classmethod
是一个错误。我希望mixins能帮上忙
但我在这种方法中看到了类似的问题:mixin类没有一个基类,它没有指定所有的公共方法和字段(an example in Django),因此IDE和Linter也无法找到定义并正确理解代码。。。我尝试使用一些公共基类,如下所示:
class FitterBase(object):
def __init__(self, whatever):
self.field = whatever
class FiterMixin(FitterBase):
def plot(self, x, y):
print(self.field)
def clear(self):
# body
@classmethod
def from_file(cls, path):
# body
class Fitter(FitterBase, FiterMixin):
pass
但解释器提出了一个错误:
TypeError: Cannot create a consistent method resolution
这个问题有什么解决办法吗?这一点非常重要,因为该类包含几十个大方法,正确的继承将非常有用
Python正在尝试为
Fitter
构造一个MRO,其中FitterBase
在FitterMixin
之前和之后;前者是因为FitterBase
列在基类的最前面,后者是因为它是FitterMixin
的父类要解决该问题,只需交换两个基类的顺序:
但是,没有理由同时列出这两个,因为
FitterMixin
已经从FitterBase
继承:更明显的是,
FitterMixin
在类中并不是真正的混合,因为您没有将它与任何东西混合。或者,不要使FitterMixin
子类FitterBase
:相关问题 更多 >
编程相关推荐