我有一組相當簡單的功能,我有多個實現,例如,一個可以由redis、mongodb或postgresql支持的數據存儲。我應該如何構造/編寫代碼,以便希望使用這些實現之一的代碼只需要該實現的依賴項,例如,它們不需要
psycopg2
如果使用的是redis后端,則安裝。
這里有一個例子。假設以下模塊,
example.py
python異常捕獲。.
class RedisExample(object):
try:
import redis
except ImportError:
print("You need to install redis-py.")
python只保留數據的某幾列、def __init__(self):
super(RedisExample, self).__init__()
class UnsatisfiedExample(object):
try:
import flibbertigibbet
except ImportError:
python只輸出一個print,print("You need to install flibbertigibbet-py")
def __init__(self):
super(UnsatisfiedExample, self).__init__()
以下是我的python shell體驗:
>>> import example
You need to install flibbertigibbet-py
python合法變量。交替地:
>>> from example import RedisExample
You need to install flibbertigibbet-py
我真的希望在嘗試實例化
UnsatisfiedExample
. 有什么共同的方法來解決這個問題嗎?我考慮過
python怎么只打印其中一行?example
一個包,每個后端都有自己的模塊并使用一個工廠函數,但我想確保我沒有遺漏更好的東西。
謝謝。
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态