1

It might seem unusual but I am making a credit card verification software in tkinter and I want to know if it is possible to access class instances via strings in python. Like I am doing below with the string variable.

This is a 'watered down' example of what i'm trying to do:

class myclass:

    def __init__(self, name):
        self.name = name

    def print_name():
        print(self.name)


adam = myclass('adam')

string = 'ad' + 'am'
string.print_name()

It gave me an AttributeError as I would expect but I don't know if there is an answer to this; I don't think there is as I couldn't find anything but it would be good if there is a way.

Crawley
  • 600
  • 2
  • 8
  • 15
  • 6
    There are ways. However the biggest question you are going to get in response to this request is, why did you think you need to do this? What is the problem you are actually trying to solve with this approach? – Rick Jan 22 '18 at 21:05
  • 1
    Typically you would store the instance in a dict: `mydict['adam'] = myclass('adam')`. Then you can access it with `mydict[string].print_name()`. – glibdud Jan 22 '18 at 21:07
  • Assuming you do actually want to do this, one good way is to [track instances in a `list` or `dict` class variable](https://stackoverflow.com/questions/12101958/keep-track-of-instances-in-python), and access them via the variable. – Rick Jan 22 '18 at 21:11
  • Also take a look at `locals()`. – match Jan 22 '18 at 21:43

0 Answers0