[英]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
. 可以说我有两个模块module1
和module2
和module1
可以有对象chair1
, chair2
和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
. 我想检查是否存在来自module2
的那些对象之一,以及是否确实存在来自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
这显然是chair1
,因为chair1
, chair2
和chair3
不在module2
globals()
中
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. Rob的答案( hasattr()
)解决了检查对象是否存在于另一个模块中的问题。 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. 第二部分,关于在我使用字典解决的对象上运行方法(类似: obj_names = {"chair1" : chair1, "chair2" : chair2, "chair3 : chair3}
而不是尝试使用global()
函数。建议在其他问题上,这是最Python化的方法,也可以使用字典来解决第一部分,例如如果对象不存在, obj_names[i] = 0
设置obj_names[i] = 0
。
Btw, for my particular problem I won't be needing more than 10 chairs so using the dictionary is not a bad option. 顺便说一句,对于我的特殊问题,我不需要超过10把椅子,因此使用字典并不是一个坏选择。 But if the problem was defined so that number of chairs can be any int, than using something like global()
would be more logical. 但是,如果定义了问题以使椅子的数量可以是任意整数,那么使用诸如global()
类的东西将更合乎逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.