0

I am trying to achieve the following (simplified from real code)

def _do_something(o1, o2, keyatt):
   x = o1.keyatt
   y = o2.keyatt
   return x == y

_do_something(srcObj, destObj, a)
_do_something(srcObj, destObj, b)

Where both objects are of the same class that have 'a' and 'b' attributes

Not sure how to pass the attributes so they are dynamically associated to the o1 and o2.

I tried _do_something(srcObj, destObj, 'a') but I get attribute error. I also tried modifying _do_something to used subscripts (i.e. o1[keyatt] but that throws a TypeError that the object is not sub-scriptable.

Is this even possible in Python? (I'm fairly new to the language.)

1 Answer 1

1

Use getattr:

def _do_something(o1, o2, keyatt):
    x = getattr(o1, keyatt)
    y = getattr(o2, keyatt)
    return x == y


class A:
    def __init__(self, a, b):
        self.a = a
        self.b = b

srcObj = A(1, 2) 
destObj = A(1, 10) 
print(_do_something(srcObj, destObj, 'a'))
print(_do_something(srcObj, destObj, 'b'))

Output:

True
False
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh... (tips hat)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.