Skip to main content
 首页 » 编程设计

python之是否可以使用变量从特定对象调用方法

2025年05月04日14xxx_UU

一段时间以来我一直在想这个问题,它似乎是 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() function 访问模块全局变量,它也给你一本字典,但大多数时候你想改用专用字典。