How to call an instance of a class without knowing the name in advance

Let's say I have different instances of a class;

class Person(object):
    def __init__(self, id):
        self.id = id

Joe = Person('123')
Sarah = Person('321')

      

Now my question is, how can I use one of the instances without knowing the name in front of my hand, for example, I could have something that asks for a name or even an ID. How do I link it to the corresponding object? Let's say that the identifier "123" is entered, how do I know that it belongs to an object Joe

and then use that object dynamically? I am using Python 3.6 if this information is very helpful.

+3


source to share


1 answer


When you study computer programming, you will probably hear the not-so-joke that there are only three important numbers: 0, 1, and infinity. In other words, you can have something or something, but if you can have more than one, you should be willing to handle any number of them.

When you can only have zero or something, putting it in a variable is fine. But this solution quickly becomes cumbersome when you may have a quantity. The solution favored by programmers is to put objects in a container, like a list or a dictionary.

For example a dictionary:

people = {"123": Person("123"), "321": Person("321")}

      

Then Joe people["123"]

.



In reality, you also want to store the person's name in the object, otherwise you cannot tell who he really represents, so add it to your class Person

. You could also add the object to the master name when it was created:

people = {}

class Person(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name
        people[id] = self

joe = Person("123", "Joe")
sarah = Person("321", "Sarah")

      

Now when you create objects, they are automatically added to the people

dict by their id and you can refer to them as such. (You can also add them by name, assuming the names are unique: even in the same dictionary, if ids and names can never collide.)

NB "Call" has a specific meaning in programming: you call a function. You don't name anything here.

+5


source







All Articles