python - 降低面向对象的python代码的圈复杂度
问题描述
我正在尝试降低代码的 cylomatic 复杂性,因为根据pylama我的定义“太复杂”,建议的解决方案包括使用字典映射调用函数。
所以我在我的面向对象代码上尝试了它,但失败了。
class trial:
def __init__(self):
self.a = 'a'
self.b = 'b'
def a(self):
return self.a
def b(self):
return self.b
def select_one(self, option):
map_func = {
1 : self.a,
2 : self.b
}
return map_func[option]()
t = trial()
print(t.select_one(1))
如果这是不可能的,那么降低圈复杂度的其他可能解决方案是什么。
解决方案
首先,应该定义字典,否则每次输入函数时__init__
都有复杂性(每次都会构建字典,这会使链接中的示例错误)O(n)
select_one
其次,您的方法与您的属性同名。改变:
class trial:
def __init__(self):
self.a = 'a'
self.b = 'b'
self.map_func = {
1 : self.f_a,
2 : self.f_b
}
def f_a(self):
return self.a
def f_b(self):
return self.b
def select_one(self, option):
return self.map_func[option]()
t = trial()
print(t.select_one(1))
推荐阅读
- c# - 使用 Udi Dahan 事件示例在 ASP.NET Core 中注册事件处理程序
- laravel - 如何在刀片中显示组件?
- python-3.x - 拆分文本并根据文本创建新列
- javascript - 将 xml 字符串转换为实际 xml 并提取特定属性
- django-rest-framework - django Swagger 无法添加参数说明
- python - 定义仅在 ast.While 对象中使用的访问方法
- typescript - 为什么 tsc 报告 SomeType 没有索引签名?
- javascript - 以顺时针方向循环一组数字
- spring - 当 Spring Security 中的会话超时时,SavedRequestAwareAuthenticationSuccessHandler 无法按预期工作
- ffmpeg - mp4s 的 ffmpeg concat 在连接处跳转并暂停几秒钟