Frank C.
Frank C.

Reputation: 8098

Dynamically use class attribute and reusable function

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

Upvotes: 0

Views: 25

Answers (1)

Mike Müller
Mike Müller

Reputation: 85492

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

Upvotes: 1

Related Questions