Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

python - A clean way to organize and load files with subclasses

I have a parent class that provides abstract functions for manipulating hardware, and a directory full of classes that subclass this parent class, and provide hardware-specific implementation (e.g. x86 functions, ARM functions...). I am looking for a Pythonic way to import the files in the directory, and instantiate them.

At the moment the parent class is in the top level directory, and the files with the child classes in a subdirectory. This can be changed, for style or ease of implementation.

Is it preferable to load all the hardware-specific classes in the subdirectory by defining a list of them in a configuration file, and iterating over that to import them? Or would it be better (more Pythonic) to do it automatically with importlib? Or does it not matter?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The basic idea of dividing the sub classes int different files and importing only what you need is very pythonic. Consider using a __init__.py file in your subclasses' folder with an import SubClass1, SubClass2, SubClass3, ...-command in it. Then you can just say in the main.py:

import folderOfSubClasses

Then the __init__.py file will be executed and you have the expected result.

I hope I could help you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...