संपादित करें: यहाँ एक संशोधित समाधान है। मुझे एहसास हुआ कि मैं अपने पिछले एक परीक्षण के दौरान गलती कर रहा था, और यह वास्तव में जिस तरह से आप उम्मीद करेंगे काम नहीं करता है। तो यहाँ एक अधिक पूर्ण समाधान है:
import os
from imp import find_module
from types import ModuleType, ClassType
def iter_plugins(package):
"""Receives package (as a string) and, for all of its contained modules,
generates all classes that are subclasses of PluginBaseClass."""
# Despite the function name, "find_module" will find the package
# (the "filename" part of the return value will be None, in this case)
filename, path, description = find_module(package)
# dir(some_package) will not list the modules within the package,
# so we explicitly look for files. If you need to recursively descend
# a directory tree, you can adapt this to use os.walk instead of os.listdir
modules = sorted(set(i.partition('.')[0]
for i in os.listdir(path)
if i.endswith(('.py', '.pyc', '.pyo'))
and not i.startswith('__init__.py')))
pkg = __import__(package, fromlist=modules)
for m in modules:
module = getattr(pkg, m)
if type(module) == ModuleType:
for c in dir(module):
klass = getattr(module, c)
if (type(klass) == ClassType and
klass is not PluginBaseClass and
issubclass(klass, PluginBaseClass)):
yield klass
मेरे पिछले समाधान था:
from types import ModuleType
import Plugins
classes = []
for item in dir(Plugins):
module = getattr(Plugins, item)
# Get all (and only) modules in Plugins
if type(module) == ModuleType:
for c in dir(module):
klass = getattr(module, c)
if isinstance(klass, PluginBaseClass):
classes.append(klass)
असल
, और भी बेहतर, आप कुछ प्रतिरूपकता चाहते हैं::
आप की तरह कुछ की कोशिश कर सकते
from types import ModuleType
def iter_plugins(package):
# This assumes "package" is a package name.
# If it's the package itself, you can remove this __import__
pkg = __import__(package)
for item in dir(pkg):
module = getattr(pkg, item)
if type(module) == ModuleType:
for c in dir(module):
klass = getattr(module, c)
if issubclass(klass, PluginBaseClass):
yield klass
आप की आवश्यकता कर सकते हैं कि वे अपने वर्ग के लिए एक जादू नाम का उपयोग करें? – nmichaels
मुझे माफ़ कर दो (मैं पाइथन के लिए अपेक्षाकृत नया हूं), लेकिन जादू वर्ग का नाम क्या है? कुछ '__Plugin1__' जैसा है? –
मुझे लगता है कि उसका मतलब कुछ नामकरण सम्मेलन था (कहें, कि सभी प्लगइन्स "प्लगइन_समूह जैसी फाइलों में हैं।py "," plugin_somethingelse.py "), ताकि आप के बजाय सभी मॉड्यूल और सभी वर्गों के माध्यम से पाशन के नाम से फ़िल्टर कर सकते हैं। व्यक्तिगत रूप से, मुझे लगता है कि इस मॉड्यूल के लिए उपयोगी हो सकता है (के रूप में वे कर रहे हैं, या हो सकता है, फ़ाइल नाम), लेकिन एक आधार वर्ग से इनहेरिट पर्याप्त एक अच्छा (यदि नहीं बेहतर) मार्कर है। – rbp