Search code examples
pythonoopconcept

Creating objects during runtime in Python


I have a problem grasping the OOP concept when it comes to creating objects during runtime. All the educational code that I have looked into yet defines specific variables e.g. 'Bob' and assigns them to a new object instance. Bob = Person()

What I have trouble understanding now is how I would design a model that creates a new object during runtime? I'm aware that my phrasing is probably faulty since all objects are generated during runtime but what I mean is that if I were to start my application in a terminal or UI how would I create new objects and manage them. I can't really define new variable names on the fly right?

An example application where I run into this design issue would be a database storing people. The user gets a terminal menu which allows him to create a new user and assign a name, salary, position. How would you instantiate that object and later call it if you want to manage it, call functions, etc.? What's the design pattern here?

Please excuse my poor understanding of the OPP model. I'm currently reading up on classes and OOP but I feel like I need to understand what my error is here before moving on. Please let me know if there is anything I should clarify.


Solution

  • Things like lists or dictionaries are great for storing dynamically generated sets of values/objects:

    class Person(object):
        def __init__(self, name):
            self.name = name
        def __repr__(self):
            print "A person named %s" % self.name
    
    people = {}
    while True:
        print "Enter a name:",
        a_name = raw_input()
    
        if a_name == 'done':
            break
    
        people[a_name] = Person(a_name)
    
        print "I made a new Person object. The person's name is %s." % a_name
    
    print repr(people)