This has probably been asked before but I couldn't find the answer to my specific question (fairly general...)
Here is an example of my question. Say my package is called 'school', and I have a class called 'book' which will have .py files along side it containing the meat of its methods. I'm not sure how to organize it all so that import statements don't look strange.
How do I organize files?
/school/
pencil/
book/
__init__.py
read.开发者_如何学编程py
burn.py
book.py
I want to be able to do something like this, since it makes the most sense:
from school import Book
b = Book(name="The Bible")
b.read()
But from the file structure above, I would have to do:
from school.book import Book
b = Book(....etc
OR
from school import book
b = book.Book(...etc
These are awkward/repetitive...what am I missing here?
You're confusing packages with classes I think. Personally, I'd put every class definition and all functions that were directly related to that class in the same .py file. For instance, reading is not an object, so I would put that as a function under the Book class, not it's own .py file. So, the structure would look something like this.
/school/
pencil.py
book.py
Inside book.py, you'd have something like this
class Book():
def __init__(self,name,author,isbn,your_variable_here):
#Your init method
def read(self,kid):
return "{0} is reading {1}.".format(kid,self.name)
def burn(self,library,lighter):
library.remove(self)
lighter.light(self)
return "Preparing to burn people."
Then, your imports look like this.
from school import book
b = book.Book("The Art of War","Sun Tzu",'999342052X','Books rock!')
b.read(ike) #This assumes ike is an object, probably of the class Student, defined and imported from elsewhere
b.burn(library,lighter) #Once more, I'm assuming these are objects for which you've imported the definition and defined them earlier.
This advantage of this system is it more closely models reality. Rather than a bunch of functions bundled by a file structure (which, as you noted, can get convoluted), you've got the grouped by classes into logical groups and constructs. However, I'd argue that Student should have the read function and library should have the checkout function, leaving books with only the burn function. But that's because books don't read, people do. And books don't check out, libraries do. That's a question of how you want to organize it.
精彩评论