[Tutor] Python OO

Alan Gauld alan.gauld at btinternet.com
Sun Mar 29 10:04:04 CEST 2015


On 29/03/15 02:16, Juan C. wrote:
> Ok, so, let me try to express what I think is 'right' here according to
> what you said.
>
> My code structure needs to be something like that:
>
> pycinema
> - package: pycinema
> - - __init__.py
> - - api.py
> - - actor.py
> - - movie.py
> - - serie.py
> - __main__.py
>

What I said only relates to serie.py, You have just introduced
a whole bunch of new concepts that we haven't discussed so far.

> 1. You said that I need to separate the API methods and calls from my code,
> so that if I need to move to another API or something like that, all the
> API code and logic will be in one place

That's one way, but what I really said was that you should separate the 
MDB API from the one you expose to your users (eg. your app). One way to 
do that is wrap the MDB API in a class of its own class MDB, say?
You can then subclass or replace the instance of that class if you 
change or use another MDB service later.

> 2. I've read in many places that a basic structure, package with all the
> logic and a single __main__.py on the folder root, is good and simple.

This is good for building a reusable module.
This is different from building an actual app. The app code could
have a different structure, and just import the modules or package
you define above.

> Let's start with something more simple, the actor.py module. Currently I
> already have this working code (http://pastebin.com/wcCnCwMc) for this
> module.
>
> How would be a good way to "convert" this API call to my api.py?
>
> Should I create an API class and have a bunch of methods like "get_actor",
> "get_movie", "get_serie", "get_season" and "get_episode"?

Yes, probably. Express the API in generic terms so that if you were 
using another one the same generic requests would apply. Do NOT call the 
API class API! Call it something that reflects what the API represents. 
In this case a Movie DB...

> In this code I'm only getting the name of the actor, but I can get other
> things from the API like birthday, deathday (when applicable),
> place_of_birth, and so on.
>
> Should my api.py get only the RAW data, in this case the JSON, and give it
> to my classes (Actor, Movie, Serie) and they (the classes) read this JSON
> and do what they need?

No, the data representation is part of the API. Your API class should 
return native Python code that your classes can use. Then if you use a 
new API that returns XML, or CSV, or even uses a local (SQL?) database, 
you can replicate the API methods in a new class but the returned data 
looks the same.


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list