面向对象的函数参数来改变变量

时间:2016-08-20 23:46:00

标签: python function oop parameters

我正在尝试将我的程序转换为面向对象的样式。目前,我有一个brandSelector()函数,它接受查询输入并查找查询和品牌数组之间的交集。但是,我试图将brandSelector()转换为通用的Selector()或交叉点查找器。例如,我可以调用类型和查询(Selector(type,query))。在这种情况下,您可以键入Selector(品牌,查询)。该附加参数定义了检查哪个数组以及设置了哪个变量 - 或者,if语句就足够了 - 但我不确定如何实现这样的系统。我将不胜感激任何解决方案或建议。谢谢,

brands = ["apple", "android", "windows"]
brand = None

def Main():
    query = input("Enter your query: ").lower()
    brand = brandSelector(query)

def brandSelector(query):
    try:
        brand = set(brands).intersection(query.split())
        brand = ', '.join(brand)
        #Check Condition After Setting
        int_cond = confirmIntersection(brand)
        if int_cond == False:
            raise NameError("No Intersection")
        return brand
    except NameError:
        print("\nNo Intersection found between query defined brand and brands array\n")
        return brandDetectionFailure()

完整代码:https://github.com/KentCoding/phoneTroubleshooting/blob/master/phoneTroubleshooting.py Python版本:v3.5.2

我的尝试:

def Main():
    init()
    query = input("Enter your query: ").lower()
    brand = Selector(brand, brands, query)
    keywordSelection(query, brand)
def Selector(var, array, query):
    try:
        #Format Brands Query
        var = set(array).intersection(query.split())
        var = ', '.join(var)
        #Check Condition After Setting
        int_cond = confirmIntersection(var)
        if int_cond == False:
            raise NameError("No Intersection")
        return var
    except NameError:
        print("\nNo Intersection found between query defined brand and brands array\n")
        return brandDetectionFailure()

但是给出了错误: UnboundLocalError: local variable 'brand' referenced before assignment

1 个答案:

答案 0 :(得分:1)

从我所看到的情况来看,没有理由将名为var的参数传递给Selector(),所以只需将其设为def Selector(array, query):并使用brand = Selector(brands, query)进行调用即可。