开发者

Beginner's conceptual question about OOP and persistence

This is a very basic question about OOP (I'm using python but really it's a c开发者_StackOverflow社区onceptual question so not really language specific). I've looked around but no tutorials or books cover this specific question. If I am unclear I apologise and would be happy to clarify anything I've written.

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

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

...to create new instances of Contact. But these are all defined before runtime. What happens when I want all these instances created on the fly by user input? Do I create new instances for each person? How would I do this from user input? Then just write all the instances to a list and pickle it? Or do you do something like...

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

...then just append 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'm not really getting (because I haven't seen it explained really anywhere). All examples I've seen don't do the above but instead create new instances for each thing/person but all of them are pre-defined and not created on the fly. I would be really grateful for someone to explain this concept to me.


Your example is exactly how it works.


Yes, that's generally how you do it - make arrays of your objects. Or some other kind of collections, depending on your language and/or framework. When creating a new object, you first create it in a temporary variable, and then insert it into your collection.

Sometimes, when you have a LOT of objects, you don't load them all at once from your persisted storage (like a DB or a file). You just load the one (or few) that you need to work with. If you load just one, it might get a special variable. Several will get a collection again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜