Python依赖注入vs组合?



我正在学习python,只是想面对相同代码的两个版本,并询问哪种方法更好。基本上我有声望类,应该绑定到每个战士对象。我的直觉告诉我,在初始化战士对象时简单地创建声望实例是最简单的。另一方面,它反对依赖注入。如有任何反馈,我将不胜感激。

class Reputation:
def __init__(self, reputation):
self._reputation = reputation
def rank(self):
if self._reputation >= 10: return "basic"
if self._reputation >= 20: return "mid"
if self._reputation >= 30: return "advanced"
def set(self, value):
if value < 0:
raise ValueError("Negative")
self._reputation = value
def get(self):
return self._reputation

组成

class Warrior:
def __init__(self, name: str, reputation: int = 0):
self.name = name
self._reputation = Reputation(reputation)
@property
def rank(self):
return self._reputation.rank()
@property
def reputation(self):
return self._reputation.get()
@reputation.setter
def reputation(self, value):
self._reputation.set(value)
def main():
warrior = Warrior("muah")
warrior.reputation += 10
print(warrior.rank)
-- basic

或者依赖注入:

class Warrior:
def __init__(self, name: str, reputation: Reputation):
self.name = name
self._reputation = reputation
@property
def rank(self):
return self._reputation.rank()
@property
def reputation(self):
return self._reputation.get()
@reputation.setter
def reputation(self, value):
self._reputation.set(value)
def main():
warrior_reputation = Reputation(reputation=11)
warrior = Warrior("muah", reputation=warrior_reputation)
warrior.reputation += 10
print(warrior.rank)
-- mid

从我的角度来看,使用依赖注入总是比使用组合更好,使用DI方式将您的类与Reputation解耦,并且更适合测试。

相关内容

  • 没有找到相关文章

最新更新