-1

Currently, I am trying to code a program in Python. I am struggling to make my system be able to decode str of classes:

E.g:

class test:
    def __init__(self, coin):
        self.coin = coin

print(test(5))
>>> <__main__.test object at 0x00D20B10>

I would want to be able to convert the string to a class, then assign it to a variable so I can:

x = eval("<__main__.test object at 0x00D20B10>")
print(x.coin)
>>> 5

My error:

Traceback (most recent call last):
    print(eval("<__main__.test object at 0x00D20B10>"))
  File "<string>", line 1
    <__main__.test object at 0x00D20B10>
    ^
SyntaxError: invalid syntax

How can I achieve that?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

0

The terms "type" and "class" mean the same: Type of string is str; string is an object of the class str.

So you don't need to convert str "type" to str "class": str already is a (built-in) class.


Note:

<__main__.test object at 0x00D20B10> is a standard way how Python prints objects of classes. It isn't an expression, so applying the eval() function to it raises an exception (your error).

If you want print something else, implement the __str__() method in your class, for example

class Test:
    def __init__(self):
        pass
    
    def __str__(self):
        return "This is an object of my class Test."

print(Test())

The output:

This is an object of my class Test.

Note that I used a capitalized name for your class — see PEP 8 — Style Guide for Python Code.

MarianD
  • 13,096
  • 12
  • 42
  • 54