首页 > 解决方案 > 降低面向对象的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))

如果这是不可能的,那么降低圈复杂度的其他可能解决方案是什么。

标签: pythonpython-3.xcyclomatic-complexity

解决方案


首先,应该定义字典,否则每次输入函数时__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))

推荐阅读