python - 在这里和那里创建具有大量导入函数的类

标签 python class oop object encapsulation

假设我在 alotoffunc.py 中有很多函数被不止一种类型的对象使用。

假设 ObjectIObjectII 以及 ObjectXI 都使用了 alotoffunc.py 中的一些函数。每个对象都使用不同的函数集,但所有对象都有变量 object.table

alotoffunc.py:

def abc(obj, x):
  return obj.table(x) * 2

def efg(obj, x):
  return obj.table(x) * obj.table(x)

def hij(obj, x, y):
  return obj.table(x) * obj.table(y)

def klm(obj, x, y):
  return obj.table(x) *2 - obj.table(y)

然后我导入函数并重载它们:

import alotoffunc

class ObjectI:
  def abc(self, x):
    return alotoffunc.abc(self, x)

  def efg(self, x):
    return alotoffunc.efg(self, x)

class ObjectII:
  def efg(self, x):
    return alotoffunc.efg(self, x)
  def klm(self, x, y): 
    return alotoffunc.klm(self, x, y)

class ObjectXI:
  def abc(self, x):
    return alotoffunc.abc(self, x)
  def klm(self, x, y):
    return alotoffunc.klm(self, x, y)

现在看起来一团糟,我应该如何构建我的对象类并安排我的 alotoffunc.py

最佳答案

(1) 您可以有一个实现所有方法的基类,然后覆盖不必要的方法以在子类中引发 NotImplementedError

(2) 你可以使用 mixin 来减少重复:

import alotoffunc

class MixinAbc:
    def abc(self, x):
        return alotoffunc.abc(self, x)

class MixinEfg:
    def efg(self, x):
        return alotoffunc.efg(self, x)

class MixinKlm:
    def klm(self, x, y):
        return alotoffunc.klm(self, x, y)

class ObjectI(MixinAbc, MixinEfg):
    pass

class ObjectII(MixinEfg, MixinKlm):
    pass    

class ObjectXI(MixinAbc, MixinKlm):
    pass

您也可以将此方法与@cpburnz 的方法结合使用。

关于python - 在这里和那里创建具有大量导入函数的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29687761/

相关文章:

python - 如何在 python 中发送 HTTPS 数据包?

python - 如何在模板中表示用户登录表单? ( Django )

c++ - 为什么这段代码在 ROOT 下编译,但没有做任何它想做的事情?

Python的字典列表值的hasattr总是返回false?

java - 公开数据结构(如类)中的成员?

python - Ubuntu 中使用 python 的屏幕录像机

python - matplotlib/Python 中条形图的单独标记条

.net - VB.NET需要一个class属性才能成为列表数组

java - 基于管道的系统的架构/设计。如何改进这段代码?

c# - 理解 C# 中的 OO 设计的那个 A-Ha 时刻