gpt4 book ai didi

Python全局/包别名实现类

转载 作者:太空宇宙 更新时间:2023-11-04 07:46:31 25 4
gpt4 key购买 nike

我有一种奇怪的感觉,这是一个简单的问题。

我希望能够“别名”一个类类型,这样我就可以在包级别交换实现。我不想让 X 量的 import X as bah 分散在我的代码中......

又名。我怎样才能做类似下面的事情:

class BaseClass(object):
def __init__(self): pass
def mymthod(self): pass
def mymthod1(self): pass
def mymthod2(self): pass

class Implementation(BaseClass):
def __init__(self):
BaseClass.__init__()

单独打包...

#I dont want thse scattered through out modules, 
#i want them in one place where i can change one and change implementations
#I tried putting it in the package init but no luck
import Implementation as BaseClassProxy


class Client(BaseClassImpl):
def __init__(self):
BaseClassImpl.__init__(self)

最佳答案

在任何文件中(最适合的地方取决于您,可能是定义了 Implementation 的地方):

BaseClassProxy = Implementation

由于类是 Python 中的一流对象,您几乎可以将它们绑定(bind)到任何变量并以相同的方式使用它们。在这种情况下,您可以为该类创建一个别名。

关于Python全局/包别名实现类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6113142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com