0

I have two instances of Python class (i simplified logic to make it shorter)

class First:
    def first_p(self):
        print('test')

    
first_instance = First()
second_instance = First()

Now i need select which one instance to use (i could do it by repeat code in if/else)

if x:
   second.first_p()
else:
   first.first_p()

But i wander how i can do it like this (it's not working)

'{}'.first_p().format(second)
3
  • Does this answer your question? Access class instance "name" dynamically in Python Commented Jul 26, 2021 at 8:50
  • @Machina OP is trying to choose which instance dynamically - not the property AFAIU. Commented Jul 26, 2021 at 8:54
  • The correct approach here is to create an explicit mapping, i.e. a dict that maps the strings to the desired objects. Commented Jul 26, 2021 at 9:32

3 Answers 3

1

I think the question can be simplified into "How could I access a variable base on the string?"

It is actually possible, depends on the scope:

# global scope
instance = globals()[second]
instance.first_p()

Ref: https://www.programiz.com/python-programming/methods/built-in/globals

# local scope, such as inside a function
instance = locals()[second]
instance.first_p()

Ref: https://www.programiz.com/python-programming/methods/built-in/locals

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

Comments

1

I think you're trying to achieve something like this:

class First:
    def first_p(self):
        return 'test' 


first_instance = First()
second_instance = First()

print(f"{ (first_instance if x else second_instance).first_p() }")

because "'{}'.first_p().format(second)" doesn't make any sense (since you're calling first_p as if it's a method in Str)

Comments

1
'{}'.format(second_instance.p() if x else first_instance.p())

Comments

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.