开发者

Python global/package alias implementation class

开发者 https://www.devze.com 2023-03-07 22:06 出处:网络
I have that strange feeling this is an easy question. I want to be able to \"alias\" a class type so i can swap out the implementation at a package level.I dont want to have X amount of import X as b

I have that strange feeling this is an easy question.

I want to be able to "alias" a class type so i can swap out the implementation at a package level. I dont want to have X amount of import X as bah scattered throughout my code...

Aka. How can I do something like the below:

class BaseClass(o开发者_开发知识库bject):
   def __init__(self):  pass
   def mymthod(self): pass
   def mymthod1(self): pass
   def mymthod2(self): pass

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

Seperate package...

#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)


In any file (where this fits best is up to you, probably wherever Implementation was defined):

BaseClassProxy = Implementation

Since classes are first class objects in Python, you can pretty much bind them to any variable and use them the same way. In this case, you can make an alias for the class.


just put something like

BaseClassProxy = Implementation

in the module, then do:

from module import BaseClassProxy
0

精彩评论

暂无评论...
验证码 换一张
取 消