首页 > 解决方案 > 我可以使用具有类属性/函数的变量吗?

问题描述

它不允许我使用具有类属性的变量。不知道如何管理这个。我需要得到 7 的答案。但我需要能够使用该变量。给我错误,

回溯(最后一次调用):文件“c:/Data/First Game (Python)/rough.py”,第 32 行,在 a.add_2(5) AttributeError: 'str' object has no attribute 'x'

我认为它无法通过我的意思提到 Me1 来识别这一点。

class Test():
    def add_2(self, y):
        print(y + 2)

Me1 = Test()

for i in range (1):
    a = "Me" + str(i+1)
    print (a)
    a.add_2(5)

标签: pythonpython-3.x

解决方案


除非您正在探索要学习的东西,否则在运行时构造类的对象没有任何意义。但是,这就是你要找的,

class Test():
    def add_2(self, y):
        print(y + 2)

Me1 = Test()

for i in range (1):
    a = "Me" + str(i+1)
    print(a)
    b = eval(a) # converting str to Class Test object
    b.add_2(5)

输出:

Me1
7

参考:https ://docs.python.org/3/library/functions.html#eval


推荐阅读