Beginner conceptual question about OOP and perseverance

This is a very simple question about OOP (I use python, but actually it is a conceptual question, therefore not very specific to the language). I looked around, but not a single textbook or book covers this specific issue. If I am unclear, I apologize and will be happy to clarify everything that I wrote.

Let's say I create a simple address book that I want to write to disk using pickle. I have a class called Contact , where __init__ takes some arguments (firstName and lastName), and I have a menu where you can create contacts, edit them, etc. For all OOP examples, I saw that they would do something like ...

 bob = Contact('Bob', 'Smith') jane = Contact('Jane', 'Smith') 

... to create new instances of Contact. But they are all determined before execution. What happens when I want all these instances to be created on the fly by the user? Create new instances for each person? How can I do this with user input? Then just write all the instances of the list and collect it? Or are you doing something like ...

 firstName, lastName = raw_input("Enter first name: "), raw_input("Enter last name: ") contact = Contact(firstName, lastName) 

... then just add the contact to the list and get new values ​​for the contact instance every time I want to add a user? This is a key concept that I really don't get (because I haven’t seen its explanation anywhere). All the examples that I saw do not do the above, but instead create new instances for each thing / person, but they are all predefined and not created on the fly. I would be very grateful if someone would explain this concept to me.

+6
oop persistence
source share
2 answers

Yes, usually how you do it - create arrays of your objects. Or some other collection, depending on your language and / or frame. When creating a new object, you first create it in a temporary variable, and then insert it into your collection.

Sometimes, when you have many objects, you don’t download them all at once from your permanent storage (for example, a database or a file). You just download the one (or several) that you need to work with. If you load only one, it can get a special variable. A few people will receive the collection again.

+1
source share

In your example, this is how it works.

+3
source share

All Articles