當前位置: 首頁>>代碼示例>>Python>>正文


Python inspect.isclass方法代碼示例

本文整理匯總了Python中inspect.isclass方法的典型用法代碼示例。如果您正苦於以下問題:Python inspect.isclass方法的具體用法?Python inspect.isclass怎麽用?Python inspect.isclass使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在inspect的用法示例。


在下文中一共展示了inspect.isclass方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_filter_introspectors

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def get_filter_introspectors(view):

    from rest_framework import filters
    try:
        from django_filters.rest_framework.backends \
            import DjangoFilterBackend as third_party_django_filter_backend
    except ImportError:
        third_party_django_filter_backend = filters.DjangoFilterBackend

    filters_map = {
        third_party_django_filter_backend: DjangoFilterBackendIntrospector,
        filters.DjangoFilterBackend: DjangoFilterBackendIntrospector,
        filters.OrderingFilter: OrderingFilterBackendIntrospector,
    }
    filter_backends = getattr(view, 'filter_backends', [])
    introspectors = []

    for backend in filter_backends:
        backend = backend if inspect.isclass(backend) else backend.__class__
        introspectors.append(
            filters_map.get(backend, BaseFilterBackendIntrospector)(view, backend)
        )

    return introspectors 
開發者ID:Arello-Mobile,項目名稱:py2swagger,代碼行數:26,代碼來源:filter.py

示例2: _get_name

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def _get_name(self):
        """
        :return: Serializer name
        :rtype: str
        """
        serializer = self.serializer

        if inspect.isclass(serializer):
            name = serializer.__name__
        else:
            name = serializer.__class__.__name__

        if name == 'DefaultSerializer' and issubclass(serializer, ModelSerializer):
            model_name = self.serializer.Meta.model.__name__
            name = '{0}Serializer'.format(model_name.strip())
        return name 
開發者ID:Arello-Mobile,項目名稱:py2swagger,代碼行數:18,代碼來源:serializer.py

示例3: _get_docstring_fields

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def _get_docstring_fields(self):
        """
        Collect custom serializer fields described in serializer docstring

        :rtype: OrderedDict
        """
        if not inspect.isclass(self.serializer):
            self.serializer = self.serializer.__class__

        parser = YAMLDocstringParser()

        for cls in inspect.getmro(self.serializer):
            parser.update(inspect.getdoc(cls))

        doc_fields = parser.schema.get('fields', OrderedDict())

        return doc_fields 
開發者ID:Arello-Mobile,項目名稱:py2swagger,代碼行數:19,代碼來源:serializer.py

示例4: __init__

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def __init__(self, *args, **kwargs):
            self.child = kwargs.pop('child', copy.deepcopy(self.child))

            self.permission_classes = self.child.permission_classes
            self.check_permission = self.child.check_permission

            self.allow_empty = kwargs.pop('allow_empty', True)

            assert self.child is not None, '`child` is a required argument.'
            assert not inspect.isclass(self.child), '`child` has not been instantiated.'

            # TODO: diagnose/address bad-super-call issue
            # pylint: disable=bad-super-call
            super(ListSerializer, self).__init__(*args, **kwargs)

            self.child.bind(field_name='', parent=self) 
開發者ID:InterSIS,項目名稱:django-rest-serializer-field-permissions,代碼行數:18,代碼來源:fields.py

示例5: type_name

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def type_name(value):
    """
    Returns a user-readable name for the type of an object

    :param value:
        A value to get the type name of

    :return:
        A unicode string of the object's type name
    """

    if inspect.isclass(value):
        cls = value
    else:
        cls = value.__class__
    if cls.__module__ in set(['builtins', '__builtin__']):
        return cls.__name__
    return '%s.%s' % (cls.__module__, cls.__name__) 
開發者ID:wbond,項目名稱:oscrypto,代碼行數:20,代碼來源:_types.py

示例6: document

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def document(self, object, name=None, *args):
        """Generate documentation for an object."""
        args = (object, name) + args
        # 'try' clause is to attempt to handle the possibility that inspect
        # identifies something in a way that pydoc itself has issues handling;
        # think 'super' and how it is a descriptor (which raises the exception
        # by lacking a __name__ attribute) and an instance.
        if inspect.isgetsetdescriptor(object): return self.docdata(*args)
        if inspect.ismemberdescriptor(object): return self.docdata(*args)
        try:
            if inspect.ismodule(object): return self.docmodule(*args)
            if inspect.isclass(object): return self.docclass(*args)
            if inspect.isroutine(object): return self.docroutine(*args)
        except AttributeError:
            pass
        if isinstance(object, property): return self.docproperty(*args)
        return self.docother(*args) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:19,代碼來源:pydoc.py

示例7: nice_classname

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def nice_classname(obj):
    """Returns a nice name for class object or class instance.

        >>> nice_classname(Exception()) # doctest: +ELLIPSIS
        '...Exception'
        >>> nice_classname(Exception) # doctest: +ELLIPSIS
        '...Exception'

    """
    if inspect.isclass(obj):
        cls_name = obj.__name__
    else:
        cls_name = obj.__class__.__name__
    mod = inspect.getmodule(obj)
    if mod:
        name = mod.__name__
        # jython
        if name.startswith('org.python.core.'):
            name = name[len('org.python.core.'):]
        return "%s.%s" % (name, cls_name)
    else:
        return cls_name 
開發者ID:ionelmc,項目名稱:nose-htmloutput,代碼行數:24,代碼來源:__init__.py

示例8: get_types_for_str

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def get_types_for_str(tp_name, frame):
    """Get a list of candidate types from a string.

    String corresponds to the tp_name as described in :
    https://docs.python.org/2/c-api/typeobj.html#c.PyTypeObject.tp_name
    as it is the name used in exception messages. It may include full path
    with module, subpackage, package but this is just removed in current
    implementation to search only based on the type name.

    Lookup uses both class hierarchy and name lookup as the first may miss
    old style classes on Python 2 and second does find them.
    Just like get_types_for_str_using_inheritance, this needs to be called
    as late as possible but because it requires a frame, there is not much
    choice anyway.
    """
    name = tp_name.split('.')[-1]
    res = set.union(
        get_types_for_str_using_inheritance(name),
        get_types_for_str_using_names(name, frame))
    assert all(inspect.isclass(t) and t.__name__ == name for t in res)
    return res 
開發者ID:SylvainDe,項目名稱:DidYouMean-Python,代碼行數:23,代碼來源:didyoumean_internal.py

示例9: generate_nodes_list

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def generate_nodes_list(nodes_dicts):
    nodes_list = []
    # append nodes with additional arguments or supervised if they exist
    visited = []
    for dct in nodes_dicts:
        klass = dct['klass']
        if type(klass) is str:
            # some of the nodes on the list may be optional
            if not hasattr(nodes, klass): continue
            # transform class name into class (needed by automatic tests)
            klass = getattr(nodes, klass)
            dct['klass'] = klass
        nodes_list.append(dct)
        visited.append(klass)
    # append all other nodes in mdp.nodes
    for attr in dir(nodes):
        if attr[0] == '_':
            continue
        attr = getattr(nodes, attr)
        if (inspect.isclass(attr)
            and issubclass(attr, mdp.Node)
            and attr not in visited
            and attr not in EXCLUDE_NODES):
            nodes_list.append(attr)
    return nodes_list 
開發者ID:ME-ICA,項目名稱:me-ica,代碼行數:27,代碼來源:test_nodes_generic.py

示例10: _get_oauth_scopes

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def _get_oauth_scopes(modules=_API_CLIENT_MODULES):
  """Retrieves all OAuth2 Scopes required for management.

  Args:
    modules: Sequence[module], a sequence of modules to extract OAuth2 scopes
        from.

  Returns:
    A list of all of the OAuth2 Scopes required for management.
  """
  scopes = []
  for client in modules:
    for name, cls in inspect.getmembers(client, inspect.isclass):
      if name.endswith('API') and hasattr(cls, 'SCOPES'):
        scopes.extend(cls.SCOPES)
  return sorted(list(set(scopes))) 
開發者ID:google,項目名稱:loaner,代碼行數:18,代碼來源:gng_impl.py

示例11: rebuild

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def rebuild(self, *_args):
        mode = self.get_mode()
        if mode == self.mode:
            return
        self.fixator.update()
        self.hide(update=False)
        for item in self.plugins:
            item.hide()
            self.remove(item)
        self.plugins = []
        if mode:
            for item in mode:
                plg = self.plugins_dict[item]
                if inspect.isclass(plg):
                    self.plugins_dict[item] = plg(self.app, self)
                    self.plugins_dict[item].update()
                self.pack(self.plugins_dict[item], fill=True)
                self.plugins_dict[item].show(update=False)
                self.plugins.append(self.plugins_dict[item])
        self.layout()
        self.show()
        self.mode = mode 
開發者ID:sk1project,項目名稱:sk1-wx,代碼行數:24,代碼來源:ctxpanel.py

示例12: _async_raise

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble, 
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
        raise SystemError("PyThreadState_SetAsyncExc failed") 
開發者ID:Cisco-Talos,項目名稱:BASS,代碼行數:14,代碼來源:thread.py

示例13: albu_builder

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def albu_builder(self, cfg):
        """Import a module from albumentations.

        It inherits some of :func:`build_from_cfg` logic.

        Args:
            cfg (dict): Config dict. It should at least contain the key "type".

        Returns:
            obj: The constructed object.
        """

        assert isinstance(cfg, dict) and 'type' in cfg
        args = cfg.copy()

        obj_type = args.pop('type')
        if mmcv.is_str(obj_type):
            if albumentations is None:
                raise RuntimeError('albumentations is not installed')
            obj_cls = getattr(albumentations, obj_type)
        elif inspect.isclass(obj_type):
            obj_cls = obj_type
        else:
            raise TypeError(
                f'type must be a str or valid type, but got {type(obj_type)}')

        if 'transforms' in args:
            args['transforms'] = [
                self.albu_builder(transform)
                for transform in args['transforms']
            ]

        return obj_cls(**args) 
開發者ID:open-mmlab,項目名稱:mmdetection,代碼行數:35,代碼來源:transforms.py

示例14: __init__

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def __init__(self, cls, modulename=''):
        if not inspect.isclass(cls):
            raise ValueError("Initialise using an object")
        self._cls = cls

        if modulename and not modulename.endswith('.'):
            modulename += '.'
        self._mod = modulename
        self._name = cls.__name__ 
開發者ID:StephanZheng,項目名稱:neural-fingerprinting,代碼行數:11,代碼來源:docscrape.py

示例15: getCmdList

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isclass [as 別名]
def getCmdList():
    """ Returns a list of all commands which are defined in this cmds.py file.
    This is done by searching for all subclasses of Cmd
    """
    return [obj for name, obj in inspect.getmembers(sys.modules[__name__]) 
                            if inspect.isclass(obj) and issubclass(obj, Cmd)][1:] 
開發者ID:francozappa,項目名稱:knob,代碼行數:8,代碼來源:cmds.py


注:本文中的inspect.isclass方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。