简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM