-3

It doesn't allow me to use a variable with an attribute of the class. Not sure how to manage this. I need the answer to come out as 7. But I need to be able to use the variable for it. gives me the error,

Traceback (most recent call last): File "c:/Data/First Game (Python)/rough.py", line 32, in a.add_2(5) AttributeError: 'str' object has no attribute 'x'

I think it is not able to recognize that by a I meant to mention 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)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • `a is string object` and `Me1 is a class object`, you can't do like this. Please specify what you want to acheive. – Prakhar May 31 '21 at 10:48
  • `a = eval("Me" + str(i + 1))` should work, but why are you doing this? this approach makes no sense. – Guy May 31 '21 at 10:49
  • Dive into class objects: https://docs.python.org/3/tutorial/classes.html#class-objects – 8349697 May 31 '21 at 10:50
  • 1
    If you `Me1.add_2(5)` you will print `7` , is this the expected result? – Ivan May 31 '21 at 10:50
  • There is nothing in your question that explains why you need to loop, or need to dynamically make a string that corresponds to a variable name... etc. If you want to refer to `Me1`, why not just do so? Why loop at all? – trincot May 31 '21 at 10:56
  • Does this answer your question? [Passing variables, creating instances, self, The mechanics and usage of classes: need explanation](https://stackoverflow.com/questions/11421659/passing-variables-creating-instances-self-the-mechanics-and-usage-of-classes) – 8349697 May 31 '21 at 11:12
  • Understood. the eval function seems to work great. This is a simplified version of a loop that I was trying to create in pygame but it wasn't working due to the string and class mismatch earlier. Thank you everyone. – Shaheryar Junejo May 31 '21 at 11:45

2 Answers2

0

From what I see the variable a is a string while the function a.add_2(5) belongs to the objects of class Test. The error is caused by the fact that you call a method of class Teston a string

0

It doesn't make any sense on constructing an object of a class at runtime unless you're exploring something to learn. But, here is what you're looking for,

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)

Output:

Me1
7

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

surya
  • 719
  • 5
  • 13