How to organize Python class definition in relation to auxiliary files for this class?

This was probably asked earlier, but I could not find the answer to my specific question (quite general ...)

Here is an example of my question. Say my package is called "school" and I have a class called "book" that will have .py files along with it containing the meat of its methods. I'm not sure how to organize all this so that import statements look weird.

How to organize files?

/school/ pencil/ book/ __init__.py read.py burn.py book.py 

I want to be able to do something like this, as this 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 

This is inconvenient / repeated ... what am I missing here?

+6
source share
1 answer

You confuse packages with classes that I think. Personally, I would put every class definition and all functions that were directly related to this class in the same .py file. For example, reading is not an object, so I would put it as a function of the Book class, and not my own .py file. Thus, the structure will look something like this.

 /school/ pencil.py book.py 

Inside book.py you will 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 import is as follows.

 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 that it models reality more closely. Instead of a set of functions connected by a file structure (which, as you have noticed, can be confusing), you group classes into logical groups and constructs. However, I would say that the Student should have a reading function, and the library should have a verification function, leaving books only with a recording function. But this is because books are not read, people are made. And books are not checked, libraries do. This is a question about how you want to organize it.

+7
source

Source: https://habr.com/ru/post/894241/


All Articles