我一直想知道这一点,它似乎是Python 会有的东西,但是可以使用与此类似的代码从不同的方法调用相同的方法吗?
这是我用来测试这个的类:
class Test(): def __init__(self,foo): self.foo = foo def method_a(): print(self.foo)
这是运行代码:
import classTest object1 = classTest.Test("Unn") object2 = classTest.Test("Tss") runThis = input("Type in either object1 or object2:") runThis.method_a()
我明白了:AttributeError:'str'对象没有属性'method_a'
我做错了什么吗?或者Python缺乏该功能?
将您的对象放在字典中:
objects = {} objects['object1'] = classTest.Test("Unn") objects['object2'] = classTest.Test("Tss") runThis = input("Type in either object1 or object2:") objects[runThis].method_a()
您还可以使用该globals()
函数访问模块全局变量,这也为您提供了字典,但大多数情况下您希望使用专用字典.