Sammy Herring Sammy Herring - 3 months ago 6
Python Question

Object orientated function parameter to alter variables

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

Answer

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