假设我在 alotoffunc.py
中有很多函数被不止一种类型的对象使用。
假设 ObjectI
和 ObjectII
以及 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/