Question

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.

Was it helpful?

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)

OTHER TIPS

You don't store each object with a variable name. Variable names are for the convenience of a programmer.

If you want a collection of objects, you use just that - a collection. Use either a list or a dictionary containing object instances, referenced by index or key respectively.

So for example, if each employee has an employee number, you might keep them in a dictionary with the employee number as a key.

For your example, you want to use a model abstraction.

If Person is a model class, you could simply do:

person = new Person()
person.name = "Bob"
person.email = "bob@aol.com"
person.save()  # this line will write to the persistent datastore (database, flat files, etc)

and then in another session, you could:

person = Person.get_by_email("bob@aol.com") # assuming you had a classmethod called 'get_by_email'

I'll try to answer as best I can here:

  1. What you're asking about is variable variable names - this isn't in Python. (I think it's in VB.Net but don't hold me to that)

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?

This is how I'd add a new person (Mickey-mouse example):

# Looping until we get a "fin" message
while True:
    print "Enter name, or "fin" to finish:"
    new_name = raw_input()
    if new_name == "fin":
        break
    print "Enter salary:"
    new_salary = raw_input()
    print "Enter position:"
    new_pos = raw_input()

    # Dummy database - the insert method would post this customer to the database
    cnn = db.connect()
    insert(cnn, new_name, new_salary, new_pos)
    cnn.commit()
    cnn.close()

Ok, so you want to now get a person from the database.

while True:
    print "Enter name of employee, or "fin" to finish:"
    emp_name = raw_input()
    if emp_name == "fin":
        break
    # Like above, the "select_employee" would retreive someone from a database
    cnn = db.connect()
    person = select_employee(cnn, emp_name)
    cnn.close()

    # Person is now a variable, holding the person you specified:
    print(person.name)
    print(person.salary)
    print(person.position)

    # It's up to you from here what you want to do

This is just a basic, rough example, but I think you get what I mean.

Also, as you can see, I didn't use a class here. A class for something like this would pretty much always be a better idea, but this was just to demonstrate how you'd change and use a variable during runtime.

You would never do Bob = Person() in a real program. Any example that shows that is arguably a bad example; it is essentially hard-coding. You will more often (in real code) do person = Person(id, name) or something like that, to construct the object using data you obtained elsewhere (read from a file, received interactively from a user, etc.). Even better would be something like employee = Person(id, name).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top