Home > Mobile >  Python use variable as object attribute
Python use variable as object attribute

Time:06-23

I am trying to use the following code:

def find_unknown_val(field, value, unknown_val):
temp_df = get_frame(field, value)
return temp_df.iloc[0].str(unknown_val)

print(find_unknown_val('Member_Name','McCarron,John','Supervisor_Name'))

This brings an error ans says TypeError: 'StringMethods' object is not callable, however it works when I use

def find_unknown_val(field, value, unknown_val):
temp_df = get_frame(field, value)
return temp_df.iloc[0].Supervisor_Name

In other words I need to pass a variable to be used as an object attribute, any Idea how to do this?

CodePudding user response:

The dot for attribute access is syntax, not an operator. You need an identifier following the dot, not an arbitrary expression.

Use getattr instead:

return getattr(temp_df.iloc[0], unknown_val)

CodePudding user response:

You can use f strings

def find_unknown_val(field, value, unknown_val):
    temp_df = get_frame(field, value)
    return temp_df.iloc[0][f"{unknown_val}"]
  • Related