python类getmembers()的实例源码

method.py 文件源码 项目:AshsSDK 作者: thehappydinoa 项目源码 文件源码 阅读 41 收藏 0 点赞 0 评论 0
def get_instance_public_methods(instance):
    """Retrieves an objects public methods

    :param instance: The instance of the class to inspect
    :rtype: dict
    :returns: A dictionary that represents an instance's methods where
        the keys are the name of the methods and the
        values are the handler to the method.
    """
    instance_members = inspect.getmembers(instance)
    instance_methods = {}
    for name, member in instance_members:
        if not name.startswith('_'):
            if inspect.ismethod(member):
                instance_methods[name] = member
    return instance_methods
registry.py 文件源码 项目:pytwitcher 作者: adongy 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def remove_plugin(self, name: str):
        plugin = self.plugins.pop(name, None)
        if plugin is None:
            return plugin

        for name, member in inspect.getmembers(plugin):
            # Remove IRC events
            if isinstance(member, event.event):
                self.remove_irc_event(member)
            # Remove listeners
            elif name.startswith(('on_', 'handle_')):
                self.remove_listener(member)

        try:
            unloader = getattr(plugin, 'unload')
        except AttributeError:
            pass
        else:
            unloader()

        return plugin
AresDocHtml.py 文件源码 项目:python-ares 作者: pynog 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def report(aresObj):
  """ Display all the HTML components """
  modulesPath = tmpplPath = os.path.join(aresObj.http['DIRECTORY'], "..", "ares", "Lib", 'html')
  sys.path.append(modulesPath)

  aresObj.title("A suite of HTML components available")
  classNames = []
  for aresMod in os.listdir(modulesPath):
    if aresMod.endswith(".py") and aresMod.startswith("AresHtml") and not aresMod.startswith("AresHtmlGraph") and aresMod != 'AresHtml.py':
      mod = __import__(aresMod.replace(".py", ""))
      for name, cls in inspect.getmembers(mod):
        if inspect.isclass(cls) and hasattr(cls, 'alias'):
          classNames.append({'Class': aresObj.href(name, 'AresDocHtmlItem',
                                                   {'html_module': aresMod, 'html_class': name, 'html_alias': cls.alias}, cssCls=''),
                             'Ares Module': aresMod,
                             #'Documentation': aresObj.external_link('Website', cls.reference),
                             })
  aresObj.table(classNames, [{'colName': 'Class', 'type': 'object'},
                             {'colName': 'Ares Module'},
                             #{'colName': 'Documentation', 'type': 'object'}
                             ], 'Ares Module Documentation')
meta.py 文件源码 项目:utils 作者: rapydo 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def get_celery_tasks_from_module(self, submodule):
        """
            Extract all celery tasks from a module.
            Celery tasks are functions decorated by @celery_app.task(...)
            This decorator transform the function into a class child of
            celery.local.PromiseProxy
        """
        tasks = {}
        functions = inspect.getmembers(submodule)
        for func in functions:

            obj_type = type(func[1])

            if obj_type.__module__ != "celery.local":
                continue

            tasks[func[0]] = func[1]
        return tasks
__init__.py 文件源码 项目:pandachaika 作者: pandabuilder 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_torrent_client(torrent_settings: Dict[str, Any]) -> TorrentClient:
    client = None
    torrent_module = None
    for module_name in modules_name:
        if module_name == torrent_settings['client']:
            if module_name not in sys.modules:
                full_package_name = '%s.%s' % ('core.downloaders.torrent', module_name)
                torrent_module = __import__(full_package_name, fromlist=[module_name])
            else:
                torrent_module = module_name
    if not torrent_module:
        return torrent_module
    for _, obj in inspect.getmembers(torrent_module):
        if inspect.isclass(obj) and hasattr(obj, 'type') and 'torrent_handler' in getattr(obj, 'type'):
            client = obj(
                torrent_settings['address'],
                torrent_settings['port'],
                torrent_settings['user'],
                torrent_settings['pass'],
                secure=not torrent_settings['no_certificate_check'],
            )
    return client
CooperativeSearch_Simulation.py 文件源码 项目:salty 作者: GaloisInc 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def update_inputs(av_states, socket_send, *input_variable_names):
    # From each input variable name, extract the function name, ids of AvStates to be passed as arguments,
    # and the corresponding function from psaltlib.Inputs. Call the function with the id-key'd AvStates as
    # arguments. Aggregate results in order in a list.
    input_state = []
    for term in input_variable_names:
        term_elements = re.split('_', term)
        function_name = term_elements[0]
        av_id_args = term_elements[1:]
        args = []
        for av_id in av_id_args:
            args.append(av_states[int(av_id)])
        args.append(socket_send)
        func = [o for o in getmembers(psaltlib.Inputs) if isfunction(o[1]) and
                    o[0] == function_name]
        input_state.append(func[0][1](*args))
    return input_state
config.py 文件源码 项目:estreamer 作者: spohara79 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def load_from(self, load_type, load_string):
        def isNotClass(element):
            return not isinstance(element, type)
        self.__load_iters([member for member in inspect.getmembers(self.caller, isNotClass)], load_type, load_string)
registry.py 文件源码 项目:PyPlanet 作者: PyPlanet 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def get_app_models(app):
    from .model import Model
    try:
        models_module = importlib.import_module('{}.models'.format(app.name))
        for name, obj in inspect.getmembers(models_module):
            if inspect.isclass(obj) and issubclass(obj, Model):
                if obj.__name__ == 'TimedModel':
                    continue
                yield name, obj
    except Exception as e:
        return list()
__init__.py 文件源码 项目:zellij 作者: nedbat 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def get_design(modname):
    """Given a module name, return a Design class."""
    fullmodname = f"zellij.design.{modname}"
    mod = importlib.import_module(fullmodname)
    classes_in_mod = []
    for _, val in inspect.getmembers(mod):
        if inspect.isclass(val):
            if inspect.getmodule(val) is mod:
                classes_in_mod.append(val)
    assert len(classes_in_mod) == 1
    return classes_in_mod[0]
load_email_templates.py 文件源码 项目:plugs-mail 作者: solocompt 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def get_members(self, app):
        return inspect.getmembers(app)
common.py 文件源码 项目:pbtk 作者: marin-m 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def iterate_proto_msg(module, base):
    for name, cls in getmembers(module):
        if isclass(cls) and issubclass(cls, Message):
            yield base + name, cls
            yield from iterate_proto_msg(cls, base + name + '.')

# Routine for saving data returned by an extractor
tailer.py 文件源码 项目:data_pipeline 作者: Yelp 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _all_message_field_names(self):
        return [
            name for name, value in getmembers(
                Message,
                lambda v: isinstance(v, property)
            )
        ]
pydoc.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def allmethods(cl):
    methods = {}
    for key, value in inspect.getmembers(cl, _is_some_method):
        methods[key] = 1
    for base in cl.__bases__:
        methods.update(allmethods(base)) # all your base are belong to us
    for key in methods.keys():
        methods[key] = getattr(cl, key)
    return methods
loader.py 文件源码 项目:eventdriventalk 作者: cachedout 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _load_mods(opts, mods, search_dir, prefix):
    '''
    opts: The seralized config file
    reaction_dir: A directory to search for reaction modules
    '''
    loaded = dict()

    for mod_to_load in mods:
        mod = imp.load_source(mod_to_load, os.path.join(search_dir, mod_to_load))

        for func_def in inspect.getmembers(mod, inspect.isfunction):
            func_mod_delimited = '{0}.{1}.{2}'.format(prefix, mod_to_load.rstrip('.py'), func_def[0])
            loaded[func_mod_delimited] = func_def[1]
    return loaded
mod_stat.py 文件源码 项目:mod_stat 作者: DadoZe 项目源码 文件源码 阅读 105 收藏 0 点赞 0 评论 0
def MYPPRINT(obj, name = None):
    import inspect, pprint
    if isinstance(obj, dict) or isinstance(obj, list):
        pprint.pprint(obj)
    elif hasattr(obj, '__call__'):
        pprint.pprint(inspect.getargspec(obj))
    else:
        pprint.pprint(inspect.getmembers(obj))
    return
arbitrage.py 文件源码 项目:bitcoin-arbitrage 作者: ucfyao 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def list_markets(self):
        logging.debug('list_markets') 
        for filename in glob.glob(os.path.join(public_markets.__path__[0], "*.py")):
            module_name = os.path.basename(filename).replace('.py', '')
            if not module_name.startswith('_'):
                module = __import__("public_markets." + module_name)
                test = eval('module.' + module_name)
                for name, obj in inspect.getmembers(test):
                    if inspect.isclass(obj) and 'Market' in (j.__name__ for j in obj.mro()[1:]):
                        if not obj.__module__.split('.')[-1].startswith('_'):
                            print(obj.__name__)
        sys.exit(0)
discovery.py 文件源码 项目:systematic-metafeatures 作者: fhpinto 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def discover_components(package, directory, base_class):
    """Discover implementations of a base class in a package.

    Parameters
    ----------
    package : str
        Package name
    directory : str
        Directory of the package to which is inspected.
    base_class : object
        Base class of objects to discover

    Returns
    -------
    list : all subclasses of `base_class` inside `directory`
    """

    components = list()

    for module_loader, module_name, ispkg in pkgutil.iter_modules(
            [directory]):
        full_module_name = "%s.%s" % (package, module_name)
        if full_module_name not in sys.modules and not ispkg:
            module = importlib.import_module(full_module_name)

            for member_name, obj in inspect.getmembers(module):
                if inspect.isclass(obj) and issubclass(base_class, obj):
                    classifier = obj
                    components.append(classifier)

    return components
recipe-362305.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def magic():
    """
    Returns a string which represents Python code that copies instance 
    variables to their local counterparts. I.e:
        var = self.var
        var2 = self.var2
    """
    s = ""
    for var, value in inspect.getmembers(sys._getframe(1).f_locals["self"]):
        if not (var.startswith("__") and var.endswith("__")):
            s += var + " = self." + var + "\n"
    return s
search.py 文件源码 项目:Harmonbot 作者: Harmon758 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self, bot):
        self.bot = bot
        # Add commands as search subcommands
        for name, command in inspect.getmembers(self):
            if isinstance(command, commands.Command) and command.parent is None and name != "search":
                self.bot.add_command(command)
                self.search.add_command(command)
        # Add search subcommands as subcommands of corresponding commands
        self.search_subcommands = ((self.imgur, "Resources.imgur"), (self.youtube, "Audio.audio"))
        for command, parent_name in self.search_subcommands:
            utilities.add_as_subcommand(self, command, parent_name, "search")
audio.py 文件源码 项目:Harmonbot 作者: Harmon758 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __init__(self, bot):
        self.bot = bot
        self.players = {}
        for name, command in inspect.getmembers(self):
            if isinstance(command, commands.Command) and command.parent is None and name != "audio":
                self.bot.add_command(command)
                self.audio.add_command(command)


问题


面经


文章

微信
公众号

扫码关注公众号