Python混合和类型、依赖项

2024-09-28 01:26:51 发布

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

我和一大班同学一起做一个项目。最初,它们被实现为只需导入的函数,如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

这个问题有什么解决办法吗?这一点非常重要,因为该类包含几十个大方法,正确的继承将非常有用


Tags: 方法函数infromselffieldplotdef
1条回答
网友
1楼 · 发布于 2024-09-28 01:26:51

Python正在尝试为Fitter构造一个MRO,其中FitterBaseFitterMixin之前和之后;前者是因为FitterBase列在基类的最前面,后者是因为它是FitterMixin的父类

要解决该问题,只需交换两个基类的顺序:

class Fitter(FitterMixin, FitterBase):
   pass

但是,没有理由同时列出这两个,因为FitterMixin已经从FitterBase继承:

class Fitter(FitterMixin):
    pass

更明显的是,FitterMixin在类中并不是真正的混合,因为您没有将它与任何东西混合。或者,不要使FitterMixin子类FitterBase

class FitterBase:
     def __init__(self, whatever):
         self.field = whatever


class FitterMixin:
    def plot(self, x, y):
         print(self.field)

    def clear(self):
        pass

    @classmethod
    def from_file(cls, path):
        pass


class Fitter(FitterBase, FitterMixin):
     pass

相关问题 更多 >

    热门问题