当前位置: 首页>>代码示例>>Python>>正文


Python issubclass函数代码示例

本文整理汇总了Python中issubclass函数的典型用法代码示例。如果您正苦于以下问题:Python issubclass函数的具体用法?Python issubclass怎么用?Python issubclass使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了issubclass函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: issubdtype

def issubdtype(arg1, arg2):
    """
    Returns True if first argument is a typecode lower/equal in type hierarchy.

    Parameters
    ----------
    arg1, arg2 : dtype_like
        dtype or string representing a typecode.

    Returns
    -------
    out : bool

    See Also
    --------
    issubsctype, issubclass_
    numpy.core.numerictypes : Overview of numpy type hierarchy.

    Examples
    --------
    >>> np.issubdtype('S1', str)
    True
    >>> np.issubdtype(np.float64, np.float32)
    False

    """
    if issubclass_(arg2, generic):
        return issubclass(dtype(arg1).type, arg2)
    mro = dtype(arg2).type.mro()
    if len(mro) > 1:
        val = mro[1]
    else:
        val = mro[0]
    return issubclass(dtype(arg1).type, val)
开发者ID:Alanchi,项目名称:numpy,代码行数:34,代码来源:numerictypes.py

示例2: setup_slaves

 def setup_slaves(self):
     field_type = self.detail.get_parameter_type()
     if issubclass(field_type, Image):
         self._setup_image_slave()
     elif issubclass(field_type, Domain):
         self._setup_comboboxentry_slave()
     elif self.detail.editor == 'file-chooser':
         self._setup_entry_with_filechooser_button_slave()
     elif self.detail.editor == 'directory-chooser':
         self._setup_entry_with_filechooser_button_slave(dir_only=True)
     elif issubclass(field_type, bool):
         self._setup_radio_slave()
     elif issubclass(field_type, (int, float, Decimal)):
         if self.detail.options:
             self._setup_options_combo_slave()
         elif self.detail.range:
             self._setup_spin_entry_slave()
         else:
             self._setup_entry_slave()
     elif issubclass(field_type, basestring):
         if self.detail.multiline:
             self._setup_text_view_slave()
         elif self.detail.combo_data:
             self._setup_comboboxentry_slave(data=self.detail.combo_data())
         else:
             self._setup_entry_slave()
     else:
         raise TypeError("ParameterData for `%s' has an invalid "
                         "type: %r" % (self.model.field_name,
                                       field_type))
开发者ID:adrianoaguiar,项目名称:stoq,代码行数:30,代码来源:parameterseditor.py

示例3: all_acceptable_memory_accesses

  def all_acceptable_memory_accesses(self, state, possible_type):
    (gadget_type, inputs, outputs, params, clobber) = possible_type

    # Always allow the LoadMem gadget for loading IP from the Stack
    if gadget_type == LoadMem and outputs[0] == self.ip and inputs[0] == self.sp:
      return True

    for mem_address, mem_value in state.in_mem.items():
      good_mem_access = False
      if not (
          # Allow the LoadMem's read
          (gadget_type == LoadMem and mem_address == state.in_regs[inputs[0]] + params[0] and state.out_regs[outputs[0]] == mem_value)

          # Allow the ArithmeticLoad's read
          or (issubclass(gadget_type, ArithmeticLoad) and mem_address == state.in_regs[inputs[0]] + params[0])

          # Allow the ArithmeticStore's read
          or (issubclass(gadget_type, ArithmeticStore) and mem_address == state.in_regs[inputs[0]] + params[0])

          # Allow loads from the SP register (i.e. pop)
          or (self.sp in state.in_regs and abs(mem_address - state.in_regs[self.sp]) < 0x1000)
      ):
        return False

    for mem_address, mem_value in state.out_mem.items():
      if not (
        # Allow the StoreMem's write
        (gadget_type == StoreMem and mem_address == state.in_regs[inputs[0]] + params[0] and mem_value == state.in_regs[inputs[1]])

        # Allow the ArithmeticStore's write
        or (issubclass(gadget_type, ArithmeticStore) and mem_address == state.in_regs[inputs[0]] + params[0])
      ):
        return False

    return True
开发者ID:KurSh,项目名称:rop_compiler,代码行数:35,代码来源:classifier.py

示例4: get_form

    def get_form(self, step=None, data=None, files=None):
        """
        Constructs the form for a given `step`. If no `step` is defined, the
        current step will be determined automatically.

        The form will be initialized using the `data` argument to prefill the
        new form. If needed, instance or queryset (for `ModelForm` or
        `ModelFormSet`) will be added too.
        """
        if step is None:
            step = self.steps.current
        # prepare the kwargs for the form instance.
        kwargs = self.get_form_kwargs(step)
        kwargs.update({
            'data': data,
            'files': files,
            'prefix': self.get_form_prefix(step, self.form_list[step]),
            'initial': self.get_form_initial(step),
        })
        if issubclass(self.form_list[step], forms.ModelForm):
            # If the form is based on ModelForm, add instance if available.
            kwargs.update({'instance': self.get_form_instance(step)})
        elif issubclass(self.form_list[step], forms.models.BaseModelFormSet):
            # If the form is based on ModelFormSet, add queryset if available.
            kwargs.update({'queryset': self.get_form_instance(step)})
        return self.form_list[step](**kwargs)
开发者ID:101studio,项目名称:django,代码行数:26,代码来源:views.py

示例5: _init_hook1

    def _init_hook1(cls, cls_name, bases, dct):

        # cls is the class to be
        # cls.__dict__ is its current dict, which may contain inherited items
        # dct is the dict represented by exactly this class (no inheritance)

        # Get CSS from the class now
        CSS = dct.get('CSS', '')

        # Create corresponding class for JS
        if issubclass(cls, LocalComponent):
            cls._make_js_proxy_class(cls_name, bases, dct)
        elif issubclass(cls, ProxyComponent):
            cls._make_js_local_class(cls_name, bases, dct)
        else:  # pragma: no cover
            raise TypeError('Expected class to inherit from '
                            'LocalComponent or ProxyComponent.')

        # Write __jsmodule__; an optimization for our module/asset system
        cls.__jsmodule__ = get_mod_name(sys.modules[cls.__module__])
        cls.JS.__jsmodule__ = cls.__jsmodule__  # need it in JS too
        cls.JS.__module__ = cls.__module__

        # Set CSS
        cls.CSS = CSS
        try:
            delattr(cls.JS, 'CSS')
        except AttributeError:
            pass
开发者ID:zoofIO,项目名称:flexx,代码行数:29,代码来源:_component2.py

示例6: test_get_url_shortener

    def test_get_url_shortener(self):
        us_settings.URL_SHORTENER_BACKEND = 'mymodule.myclass'
        try:
            with warnings.catch_warnings(record=True) as w:
                self.assertEquals(get_url_shortener(), default_backend)
                self.assertTrue(issubclass(w[-1].metatype, RuntimeWarning))
                self.assertEquals(
                    str(w[-1].message),
                    'mymodule.myclass backend cannot be imported')
        except AttributeError:
            # Fail under Python2.5, because of'warnings.catch_warnings'
            pass

        us_settings.URL_SHORTENER_BACKEND = 'gstudio.tests.custom_url_shortener'
        try:
            with warnings.catch_warnings(record=True) as w:
                self.assertEquals(get_url_shortener(), default_backend)
                self.assertTrue(issubclass(w[-1].metatype, RuntimeWarning))
                self.assertEquals(
                    str(w[-1].message),
                    'This backend only exists for testing')
        except AttributeError:
            # Fail under Python2.5, because of'warnings.catch_warnings'
            pass

        us_settings.URL_SHORTENER_BACKEND = 'gstudio.url_shortener'\
                                            '.backends.default'
        self.assertEquals(get_url_shortener(), default_backend)
开发者ID:Big-Data,项目名称:gnowsys-studio,代码行数:28,代码来源:url_shortener.py

示例7: test_subclass

 def test_subclass(self):
     self.assertTrue(issubclass(dict, aiozmq.rpc.AbstractHandler))
     self.assertIsInstance({}, aiozmq.rpc.AbstractHandler)
     self.assertFalse(issubclass(object, aiozmq.rpc.AbstractHandler))
     self.assertNotIsInstance(object(), aiozmq.rpc.AbstractHandler)
     self.assertNotIsInstance('string', aiozmq.rpc.AbstractHandler)
     self.assertNotIsInstance(b'bytes', aiozmq.rpc.AbstractHandler)
开发者ID:TadLeonard,项目名称:aiozmq,代码行数:7,代码来源:rpc_test.py

示例8: create

    def create(self, parameter_type):
        if issubclass(parameter_type, EnumParameter):
            class TestParameterEnum(parameter_type):
                def __init__(self):
                    parameter_type.__init__(self)
                    self.value = parameter_type.default_value(self)

            return TestParameterEnum()

        elif issubclass(parameter_type, BooleanParameter):
            class TestParameterBoolean(parameter_type):
                def __init__(self):
                    parameter_type.__init__(self)
                    self.value = parameter_type.default_value(self)

            return TestParameterBoolean()

        elif issubclass(parameter_type, Parameter):
            class TestParameter(parameter_type):
                def __init__(self):
                    parameter_type.__init__(self)

            return TestParameter()

        else:
            raise TypeError('Parameter type %s unknown!' %
                            str(type(parameter_type)))
开发者ID:bchretien,项目名称:voidwalker,代码行数:27,代码来源:interface.py

示例9: describe

def describe(value):
  """Describe any value as a descriptor.

  Helper function for describing any object with an appropriate descriptor
  object.

  Args:
    value: Value to describe as a descriptor.

  Returns:
    Descriptor message class if object is describable as a descriptor, else
    None.
  """
  from . import remote
  if isinstance(value, types.ModuleType):
    return describe_file(value)
  elif callable(value) and hasattr(value, 'remote'):
    return describe_method(value)
  elif isinstance(value, messages.Field):
    return describe_field(value)
  elif isinstance(value, messages.Enum):
    return describe_enum_value(value)
  elif isinstance(value, type):
    if issubclass(value, messages.Message):
      return describe_message(value)
    elif issubclass(value, messages.Enum):
      return describe_enum(value)
    elif issubclass(value, remote.Service):
      return describe_service(value)
  return None
开发者ID:GdZ,项目名称:scriptfile,代码行数:30,代码来源:descriptor.py

示例10: create_views

def create_views(sender, **kwargs):
    cursor = connection.cursor()
    app = kwargs['app']
    if type(app) == str:
        import sys
        app = getattr(sys.modules[app], 'models')
    for model in models.get_models(app):
        if issubclass(model, View):
            # Check if view exists
            sql = model.create_check()
            cursor.execute(*sql)
            result = cursor.fetchone()
            if not result[0]:
                # Create View
                sql = model.create_sql()
                cursor.execute(*sql)
            if issubclass(model, MatView):
                sql = MatView.storedproc_check()
                expected_resp = sql[2]
                sql = sql[:2]
                cursor.execute(*sql)
                res = cursor.fetchall()
                if res[0][0] != expected_resp:
                    for sql in MatView.storedproc_sql():
                        cursor.execute(sql, ())
                func = model.create_matview()
                try:
                    cursor.execute(*func)
                    transaction.commit()
                except DatabaseError as e:
                    if e.message.startswith('MatView') and e.message.find('already exists') != -1:
                        transaction.rollback()
                    else:
                        raise
开发者ID:spuriousdata,项目名称:django-pgfields,代码行数:34,代码来源:__init__.py

示例11: register

    def register(self, provider_class):
        """
        Registers a provider with the site.
        """
        if not issubclass(provider_class, BaseProvider):
            raise TypeError('%s is not a subclass of BaseProvider' % provider_class.__name__)

        if provider_class in self._registered_providers:
            raise AlreadyRegistered('%s is already registered' % provider_class.__name__)

        if issubclass(provider_class, DjangoProvider):
            # set up signal handler for cache invalidation
            signals.post_save.connect(
                self.invalidate_stored_oembeds,
                sender=provider_class._meta.model
            )

        # don't build the regex yet - if not all urlconfs have been loaded
        # and processed at this point, the DjangoProvider instances will fail
        # when attempting to reverse urlpatterns that haven't been created.
        # Rather, the regex-list will be populated once, on-demand.
        self._registered_providers.append(provider_class)

        # flag for re-population
        self.invalidate_providers()
开发者ID:BergSoft,项目名称:djbookru,代码行数:25,代码来源:sites.py

示例12: get_build_from_file

def get_build_from_file (platform, file_name, name):
    gub_name = file_name.replace (os.getcwd () + '/', '')
    logging.verbose ('reading spec: %(gub_name)s\n' % locals ())
    # Ugh, FIXME
    # This loads gub/specs/darwin/python.py in PYTHON. namespace,
    # overwriting the PYTHON. namespace from gub/specs/python.py
    # Current workaround: always/also use __darwin etc. postfixing
    # of class names, also in specs/darwin/ etc.
    warnings.filterwarnings ('ignore', '''Parent module 'python-2' ''')
    module = misc.load_module (file_name, name)
    # cross/gcc.py:Gcc will be called: cross/Gcc.py,
    # to distinguish from specs/gcc.py:Gcc.py
    base = os.path.basename (name)
    class_name = ((base[0].upper () + base[1:])
                  .replace ('-', '_')
                  .replace ('.', '_')
                  .replace ('++', '_xx_')
                  .replace ('+', '_x_')
                  + ('-' + platform).replace ('-', '__'))
    logging.debug ('LOOKING FOR: %(class_name)s\n' % locals ())
    cls = misc.most_significant_in_dict (module.__dict__, class_name, '__')
    if (platform == 'tools32'
        and (not cls or issubclass (cls, target.AutoBuild))):
        cls = misc.most_significant_in_dict (module.__dict__, class_name.replace ('tools32', 'tools'), '__')
    if ((platform == 'tools' or platform == 'tools32')
        and (issubclass (cls, target.AutoBuild)
             and not issubclass (cls, tools.AutoBuild)
             and not issubclass (cls, tools32.AutoBuild))):
        cls = None
    return cls
开发者ID:alepharchives,项目名称:gub,代码行数:30,代码来源:dependency.py

示例13: __call__

    def __call__(self, name, *args, **kwargs):
        if "observed" in kwargs:
            raise ValueError(
                "Observed Bound distributions are not supported. "
                "If you want to model truncated data "
                "you can use a pm.Potential in combination "
                "with the cumulative probability function. See "
                "pymc3/examples/censored_data.py for an example."
            )

        transform = kwargs.pop("transform", "infer")
        if issubclass(self.distribution, Continuous):
            return _ContinuousBounded(
                name,
                self.distribution,
                self.lower,
                self.upper,
                transform,
                *args,
                **kwargs
            )
        elif issubclass(self.distribution, Discrete):
            return _DiscreteBounded(
                name,
                self.distribution,
                self.lower,
                self.upper,
                transform,
                *args,
                **kwargs
            )
        else:
            raise ValueError("Distribution is neither continuous nor discrete.")
开发者ID:pymc-devs,项目名称:pymc3,代码行数:33,代码来源:bound.py

示例14: does_match_definition

def does_match_definition(given, main, secondary):
    """implementation details"""
    assert isinstance(secondary, tuple)
    assert len(secondary) == 2  # general solution could be provided
    types = decompose_type(given)

    if isinstance(types[0], main):
        return True

    if len(types) >= 2:
        cond1 = isinstance(types[0], main)
        cond2 = isinstance(types[1], secondary)
        cond3 = isinstance(types[1], main)
        cond4 = isinstance(types[0], secondary)
        if (cond1 and cond2) or (cond3 and cond4):
            return True

        if len(types) >= 3:
            classes = set([tp.__class__ for tp in types[:3]])
            desired = set([main] + list(secondary))
            diff = classes.symmetric_difference(desired)
            if not diff:
                return True
            if len(diff) == 2:
                items = list(diff)
                return (
                    issubclass(
                        items[0], items[1]) or issubclass(items[1], items[0]))
            return False
    else:
        return False
开发者ID:Kitware,项目名称:ITK,代码行数:31,代码来源:type_traits.py

示例15: log_wal_fetch_failures_on_error

    def log_wal_fetch_failures_on_error(exc_tup, exc_processor_cxt):
        def standard_detail_message(prefix=''):
            return (prefix + '  There have been {n} attempts to fetch wal '
                    'file {url} so far.'.format(n=exc_processor_cxt, url=url))
        typ, value, tb = exc_tup
        del exc_tup

        # Screen for certain kinds of known-errors to retry from
        if issubclass(typ, socket.error):
            socketmsg = value[1] if isinstance(value, tuple) else value

            logger.info(
                msg='Retrying fetch because of a socket error',
                detail=standard_detail_message(
                    "The socket error's message is '{0}'."
                    .format(socketmsg)))
        elif (issubclass(typ, boto.exception.S3ResponseError) and
              value.error_code == 'RequestTimeTooSkewed'):
            logger.info(msg='Retrying fetch because of a Request Skew time',
                        detail=standard_detail_message())
        else:
            # For all otherwise untreated exceptions, report them as a
            # warning and retry anyway -- all exceptions that can be
            # justified should be treated and have error messages
            # listed.
            logger.warning(
                msg='retrying WAL file fetch from unexpected exception',
                detail=standard_detail_message(
                    'The exception type is {etype} and its value is '
                    '{evalue} and its traceback is {etraceback}'
                    .format(etype=typ, evalue=value,
                            etraceback=''.join(traceback.format_tb(tb)))))

        # Help Python GC by resolving possible cycles
        del tb
开发者ID:runway20,项目名称:wal-e,代码行数:35,代码来源:s3_util.py


注:本文中的issubclass函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。