简体   繁体   中英

How to check if arbitrary class instance exists and call its method from another module?

Lets say I have two modules module1 and module2 and module1 can have objects chair1 , chair2 and chair3 . I want to check if one of those objects exist from module2 and if it does exist run a method on it also from module2 . Something like:

# module2
if ("chair" + str(i)) in globals():
    globals()["chair" + str(i)].carve() # i = 1, 2 or 3

This obviously won't work because chair1 , chair2 and chair3 are not in globals() of module2

What is the best approach to solve this?

EDIT:

Rob's answer ( hasattr() ) solves the problem of checking if the object exists in the other module. The second part, about running methods on objects I solved by using dictionary (something like: obj_names = {"chair1" : chair1, "chair2" : chair2, "chair3 : chair3} instead of trying to use global() function. As recommended on some other issue this is the most pythonic approach. First part can also be solved with dictionary, like setting obj_names[i] = 0 if the object doesn't exist.

Btw, for my particular problem I won't be needing more than 10 chairs so using the dictionary is not a bad option. But if the problem was defined so that number of chairs can be any int, than using something like global() would be more logical.

Try hasattr() :

# module2.py
import module1

if hasattr(module1, "chair1"):
    module1.chair1.carve()

You can use dir :

if "chair1" in dir(module1):
    ...

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