alv*_*vas 13 python oop encapsulation class object
假设我有很多函数,alotoffunc.py它被多于一种类型的对象使用.
比方说,ObjectI和ObjectII与ObjectXI所有在使用一些功能alotoffunc.py.每个Object都使用不同的函数集,但所有对象都有变量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)
Run Code Online (Sandbox Code Playgroud)
然后我导入函数并重载它们:
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)
Run Code Online (Sandbox Code Playgroud)
它现在看起来像一个大混乱,我应该如何建立我的对象类并安排我的alotoffunc.py?
(1)你可以有一个实现所有方法的基类,然后重写不必要的基类来NotImplementedError在子类中引发a .
(2)你可以使用mixins来减少重复:
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
Run Code Online (Sandbox Code Playgroud)
您也可以将此方法与@cpburnz的方法结合使用.
最简单的方法是将所需的函数作为实例方法直接绑定到其定义中的类.请注意,每个函数都将self作为第一个参数接收.
import alotoffunc
class ObjectI:
abc = alotoffunc.abc
efg = alotoffunc.efg
class ObjectII:
efg = alotoffunc.efg
klm = alotoffunc.klm
class ObjectXI:
abc = alotoffunc.abc
klm = alotoffunc.klm
Run Code Online (Sandbox Code Playgroud)
如果没有针对各种函数的清晰逻辑分组,这可以是定义混合类的更简单方法.分组确实取决于您的用例,因此混合方法可以根据情况更好.
如果我想避免使用mixins,也许是为了最小化代码的不透明度,我会这样做:
class ObjectI:
from alotoffunc import abc, efg
class ObjectII:
from alotoffunc import efg, klm
class ObjectXI:
from alotoffunc import abc, klm
Run Code Online (Sandbox Code Playgroud)
每当您创建类的实例时,导入的方法都会自动绑定.换句话说,默认情况下它们是实例方法.
如果您希望它们是静态方法,请使用staticmethod以下内容:
class ObjectI:
from alotoffunc import abc, efg
abc = staticmethod(abc)
Run Code Online (Sandbox Code Playgroud)
此外,我不会过多担心因使用这些多个import语句而导致的性能问题,因为Python非常智能,只能运行一次导入的模块,然后将其保存在内存中,以备日后需要时使用.
如果你要导入的函数有某种逻辑分组,那么你绝对应该使用mixins,或者将函数组织成单独的"mixin模块",这样你甚至可以做到from mixinmodule import *.对于mixin级方法,我认为常规import语句比from-import更好,除非你的函数名很长,你只想输入一次!
| 归档时间: |
|
| 查看次数: |
434 次 |
| 最近记录: |