Chjul
Chjul

Reputation: 437

Use string to get attribute value python

I have this :

class A:
    def __getattr__(self, name):
        if name == 'a'
             return 'this'
        else:
             return 'that'

I would like to create another class that use 'class A' and use a string as the future attributes of 'A' like this:

class B:
    def use_a(self, attributes='a'):
         a = A().attributes
         return a

I would like that the method use_a(class B) return 'this' if i set attributes to 'a', but it doesn't work and returns 'that'. But i try to do a gettattr it doesn't work either. How can I do that ? Thanks a lot

Upvotes: 0

Views: 673

Answers (1)

chepner
chepner

Reputation: 531055

__getattr__ is called if A().a doesn't exist. You still need to use getattr if the attribute itself is a variable.

def use_a(self, attribute='a'):
    a = getattr(A(), attribute)
    return a

Upvotes: 1

Related Questions