Object orientated function parameter to alter variables

∥☆過路亽.° 提交于 2019-12-23 01:36:10

问题


I am trying convert my program to an object orientated style. Currently, I have a brandSelector() function which takes the query input and finds an intersection between the query and the brands array. However, I am trying to convert the brandSelector() to a generic Selector() or intersection finder. For example, I could call with type and the query (Selector(type, query)). In this instance you would type Selector(brand, query). That additional parameter defines which array is checked and which variable is set - alternatively, an if statement would suffice - but I am not sure how to implement such a system. I would appreciate any solutions or advice. Thanks,

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()

Full Code: https://github.com/KentCoding/phoneTroubleshooting/blob/master/phoneTroubleshooting.py Python Version: v3.5.2

My Attempt:

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()

But gives the error: UnboundLocalError: local variable 'brand' referenced before assignment


回答1:


From what I can see, there's no reason to have the argument named var being passed to Selector(), so just make it def Selector(array, query): and call it with brand = Selector(brands, query).



来源:https://stackoverflow.com/questions/39059671/object-orientated-function-parameter-to-alter-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!