0

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

1
  • can you make the program more clearer and explained? Commented Jun 19, 2020 at 16:10

1 Answer 1

1

__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
Sign up to request clarification or add additional context in comments.

2 Comments

a is an attribute, attribute is not. attribute is a variable whose value is the name of an attribute.
That is, A().x is equivalent to getattr(A(), 'x'), not getattr(A(), x).

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.