python类InstanceType()的实例源码

rebuild.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def latestVersionOf(self, anObject):
        """Get the latest version of an object.

        This can handle just about anything callable; instances, functions,
        methods, and classes.
        """
        t = type(anObject)
        if t == types.FunctionType:
            return latestFunction(anObject)
        elif t == types.MethodType:
            if anObject.im_self is None:
                return getattr(anObject.im_class, anObject.__name__)
            else:
                return getattr(anObject.im_self, anObject.__name__)
        elif t == types.InstanceType:
            # Kick it, if it's out of date.
            getattr(anObject, 'nothing', None)
            return anObject
        elif t == types.ClassType:
            return latestClass(anObject)
        else:
            log.msg('warning returning anObject!')
            return anObject
explorer.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __init__(self, method, identifier):

        function = method.im_func
        if type(function) is types.InstanceType:
            function = function.__call__.im_func

        ExplorerFunction.__init__(self, function, identifier)
        self.id = id(method)
        self.klass = explorerPool.getExplorer(method.im_class,
                                              identifier + '.im_class')
        self.self = explorerPool.getExplorer(method.im_self,
                                             identifier + '.im_self')

        if method.im_self:
            # I'm a bound method -- eat the 'self' arg.
            self.signature.discardSelf()
visualstudio_py_debugger.py 文件源码 项目:pythonVSCode 作者: DonJayamanne 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
        for name in names:
            if name not in treated:
                try:
                    obj = objects[name]
                    try:
                        if sys.version[0] == '2' and type(obj) is types.InstanceType:
                            type_name = "instance (" + obj.__class__.__name__ + ")"
                        else:
                            type_name = type(obj).__name__
                    except:
                        type_name = 'unknown'
                except:
                    if skip_unknown:
                        continue
                    obj = SynthesizedValue('<undefined>', len_value=0)
                    type_name = 'unknown'
                vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
                treated.add(name)
visualstudio_py_debugger.py 文件源码 项目:pythonVSCode 作者: DonJayamanne 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
        for name in names:
            if name not in treated:
                try:
                    obj = objects[name]
                    try:
                        if sys.version[0] == '2' and type(obj) is types.InstanceType:
                            type_name = "instance (" + obj.__class__.__name__ + ")"
                        else:
                            type_name = type(obj).__name__
                    except:
                        type_name = 'unknown'
                except:
                    if skip_unknown:
                        continue
                    obj = SynthesizedValue('<undefined>', len_value=0)
                    type_name = 'unknown'
                vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
                treated.add(name)
remote.py 文件源码 项目:SameKeyProxy 作者: xzhou 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _invokePYRO(self, *vargs, **kargs):
        result = unwrap(apply(Pyro.core.DynamicProxyWithAttrs._invokePYRO,
                              tuple([self] + wrap(list(vargs))), wrap(kargs)))

        if type(result) is types.InstanceType and \
           isinstance(result, Error) or \
           isinstance(result, Pyro.errors.PyroError) or \
           isinstance(result, ProtocolError):
            msg = str(result)
            type_name = msg[: msg.find(' ')]

            if type_name == 'exceptions.IndexError':
                try:
                    real_type = eval(type_name)
                    msg       = msg.split('\n')[0]
                    result    = real_type(msg[msg.find(':') + 2 :])
                except:
                    pass

            raise result
        else:
            return result
remote.py 文件源码 项目:SameKeyProxy 作者: xzhou 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def unwrap(value):
    t = type(value)
    if t is types.InstanceType and isinstance(value, DynamicProxy):
        if pyro_daemon:
            try:
                return pyro_daemon.getLocalObject(value.objectID)
            except KeyError:
                pass
        return value
    elif t is types.ListType:
        for i in range(len(value)):
            value[i] = unwrap(value[i])
    elif t is types.TupleType:
        value = list(value)
        for i in range(len(value)):
            value[i] = unwrap(value[i])
        return tuple(value)
    elif t is types.DictType:
        for k, v in value.items():
            value[k] = unwrap(v)
    return value
action.py 文件源码 项目:apocalypse 作者: dhoomakethu 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def register(cls, action):
        action_logger.info("Registering action :%s" % action)
        if isinstance(action, (types.FunctionType, staticmethod)):
            name = action.__name__
            cls._actions[name.upper()] = action
            setattr(cls, name, action)
        elif isinstance(action, types.ClassType) and hasattr(action, "__call__"):
            name = action.__name__
            action = action()
            cls._actions[name.upper()] = action
            setattr(cls, name, action)
        elif (isinstance(action, (types.InstanceType, types.ObjectType))
              and hasattr(action, "__call__")):
            if isinstance(action, type):
                name = action.__name__
                action = action()
            else:
                name = action.__class__.__name__
            cls._actions[name.upper()] = action
            setattr(cls, name, action)

        else:
            name = str(action)
            action_logger.error("Error registering action :%s" % action)
            raise UnknownAction("unable to register action %s!!" %name)
executor.py 文件源码 项目:apocalypse 作者: dhoomakethu 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def register(cls, event):
        exe_logger.info("Registering event :%s" % event)
        if isinstance(event, (types.FunctionType, staticmethod)):
            name = event.__name__
            cls._chaos_events[name.upper()] = event
            setattr(cls, name, event)
        elif isinstance(event, types.ClassType) and hasattr(event, "__call__"):
            name = event.__name__
            event = event()
            cls._chaos_events[name.upper()] = event
            setattr(cls, name, event)
        elif (isinstance(event, (types.InstanceType, types.ObjectType))
              and hasattr(event, "__call__")):
            if isinstance(event, type):
                name = event.__name__
                event = event()
            else:
                name = event.__class__.__name__
            cls._chaos_events[name.upper()] = event
            setattr(cls, name, event)

        else:
            name = str(event)
            exe_logger.error("Error registering event :%s" % event)
            raise UnknownChaosEvent("unable to register event %s!!" % name)
_base.py 文件源码 项目:AshsSDK 作者: thehappydinoa 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _invoke_callbacks(self):
        for callback in self._done_callbacks:
            try:
                callback(self)
            except Exception:
                LOGGER.exception('exception calling callback for %r', self)
            except BaseException:
                # Explicitly let all other new-style exceptions through so
                # that we can catch all old-style exceptions with a simple
                # "except:" clause below.
                #
                # All old-style exception objects are instances of
                # types.InstanceType, but "except types.InstanceType:" does
                # not catch old-style exceptions for some reason.  Thus, the
                # only way to catch all old-style exceptions without catching
                # any new-style exceptions is to filter out the new-style
                # exceptions, which all derive from BaseException.
                raise
            except:
                # Because of the BaseException clause above, this handler only
                # executes for old-style exception objects.
                LOGGER.exception('exception calling callback for %r', self)
traitlets.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def error(self, obj, value):
        kind = type(value)
        if six.PY2 and kind is InstanceType:
            msg = 'class %s' % value.__class__.__name__
        else:
            msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )

        if obj is not None:
            e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
                % (self.name, class_of(obj),
                   self.info(), msg)
        else:
            e = "The '%s' trait must be %s, but a value of %r was specified." \
                % (self.name, self.info(), msg)

        raise TraitError(e)
rebuild.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def latestVersionOf(self, anObject):
        """Get the latest version of an object.

        This can handle just about anything callable; instances, functions,
        methods, and classes.
        """
        t = type(anObject)
        if t == types.FunctionType:
            return latestFunction(anObject)
        elif t == types.MethodType:
            if anObject.im_self is None:
                return getattr(anObject.im_class, anObject.__name__)
            else:
                return getattr(anObject.im_self, anObject.__name__)
        elif t == types.InstanceType:
            # Kick it, if it's out of date.
            getattr(anObject, 'nothing', None)
            return anObject
        elif t == types.ClassType:
            return latestClass(anObject)
        else:
            log.msg('warning returning anObject!')
            return anObject
explorer.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def __init__(self, method, identifier):

        function = method.im_func
        if type(function) is types.InstanceType:
            function = function.__call__.im_func

        ExplorerFunction.__init__(self, function, identifier)
        self.id = id(method)
        self.klass = explorerPool.getExplorer(method.im_class,
                                              identifier + '.im_class')
        self.self = explorerPool.getExplorer(method.im_self,
                                             identifier + '.im_self')

        if method.im_self:
            # I'm a bound method -- eat the 'self' arg.
            self.signature.discardSelf()
gantt.py 文件源码 项目:Python-Gantt 作者: asisrai23 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def save(self, width='100%', height='100%'):
        """ Write the XML string to **filename**. """
        test = False
        import io

        # Fix height and width
        self['height'] = height
        self['width'] = width

        if sys.version_info[0] == 2:
            test = type(self.filename) == types.FileType or type(self.filename) == types.InstanceType
        elif sys.version_info[0] == 3:
            test = type(self.filename) == io.TextIOWrapper

        if test:
            self.write(self.filename)
        else:
            fileobj = io.open(str(self.filename), mode='w', encoding='utf-8')
            self.write(fileobj)
            fileobj.close()



############################################################################
traitlets.py 文件源码 项目:Repobot 作者: Desgard 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def error(self, obj, value):
        kind = type(value)
        if six.PY2 and kind is InstanceType:
            msg = 'class %s' % value.__class__.__name__
        else:
            msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )

        if obj is not None:
            e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
                % (self.name, class_of(obj),
                   self.info(), msg)
        else:
            e = "The '%s' trait must be %s, but a value of %r was specified." \
                % (self.name, self.info(), msg)

        raise TraitError(e)
oinspect.py 文件源码 项目:Repobot 作者: Desgard 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def pdef(self, obj, oname=''):
        """Print the call signature for any callable object.

        If the object is a class, print the constructor information."""

        if not callable(obj):
            print('Object is not callable.')
            return

        header = ''

        if inspect.isclass(obj):
            header = self.__head('Class constructor information:\n')
        elif (not py3compat.PY3) and type(obj) is types.InstanceType:
            obj = obj.__call__

        output = self._getdef(obj,oname)
        if output is None:
            self.noinfo('definition header',oname)
        else:
            print(header,self.format(output), end=' ')

    # In Python 3, all classes are new-style, so they all have __init__.
visualstudio_py_debugger.py 文件源码 项目:HomeAutomation 作者: gs2671 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
        for name in names:
            if name not in treated:
                try:
                    obj = objects[name]
                    try:
                        if sys.version[0] == '2' and type(obj) is types.InstanceType:
                            type_name = "instance (" + obj.__class__.__name__ + ")"
                        else:
                            type_name = type(obj).__name__
                    except:
                        type_name = 'unknown'
                except:
                    if skip_unknown:
                        continue
                    obj = SynthesizedValue('<undefined>', len_value=0)
                    type_name = 'unknown'
                vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
                treated.add(name)
_base.py 文件源码 项目:pipenv 作者: pypa 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _invoke_callbacks(self):
        for callback in self._done_callbacks:
            try:
                callback(self)
            except Exception:
                LOGGER.exception('exception calling callback for %r', self)
            except BaseException:
                # Explicitly let all other new-style exceptions through so
                # that we can catch all old-style exceptions with a simple
                # "except:" clause below.
                #
                # All old-style exception objects are instances of
                # types.InstanceType, but "except types.InstanceType:" does
                # not catch old-style exceptions for some reason.  Thus, the
                # only way to catch all old-style exceptions without catching
                # any new-style exceptions is to filter out the new-style
                # exceptions, which all derive from BaseException.
                raise
            except:
                # Because of the BaseException clause above, this handler only
                # executes for old-style exception objects.
                LOGGER.exception('exception calling callback for %r', self)
commontest.py 文件源码 项目:rdiff-backup 作者: sol1 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def getrefs(i, depth):
    """Get the i'th object in memory, return objects that reference it"""
    import sys, gc, types
    o = sys.getobjects(i)[-1]
    for d in range(depth):
        for ref in gc.get_referrers(o):
            if type(ref) in (types.ListType, types.DictType,
                                types.InstanceType):
                if type(ref) is types.DictType and ref.has_key('copyright'):
                    continue
                o = ref
                break
        else:
            print "Max depth ", d
            return o
    return o
visualstudio_py_debugger.py 文件源码 项目:xidian-sfweb 作者: Gear420 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
        for name in names:
            if name not in treated:
                try:
                    obj = objects[name]
                    try:
                        if sys.version[0] == '2' and type(obj) is types.InstanceType:
                            type_name = "instance (" + obj.__class__.__name__ + ")"
                        else:
                            type_name = type(obj).__name__
                    except:
                        type_name = 'unknown'
                except:
                    if skip_unknown:
                        continue
                    obj = SynthesizedValue('<undefined>', len_value=0)
                    type_name = 'unknown'
                vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
                treated.add(name)
util.py 文件源码 项目:Deploy_XXNET_Server 作者: jzp820927 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def try_serialize_handler(handler):
  """Try to serialize map/reduce handler.

  Args:
    handler: handler function/instance. Handler can be a function or an
      instance of a callable class. In the latter case, the handler will
      be serialized across slices to allow users to save states.

  Returns:
    serialized handler string or None.
  """
  if (isinstance(handler, types.InstanceType) or
      (isinstance(handler, object) and
       not inspect.isfunction(handler) and
       not inspect.ismethod(handler)) and
      hasattr(handler, "__call__")):
    return pickle.dumps(handler)
  return None
visualstudio_py_debugger.py 文件源码 项目:skojjt 作者: martin-green 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
        for name in names:
            if name not in treated:
                try:
                    obj = objects[name]
                    try:
                        if sys.version[0] == '2' and type(obj) is types.InstanceType:
                            type_name = "instance (" + obj.__class__.__name__ + ")"
                        else:
                            type_name = type(obj).__name__
                    except:
                        type_name = 'unknown'
                except:
                    if skip_unknown:
                        continue
                    obj = SynthesizedValue('<undefined>', len_value=0)
                    type_name = 'unknown'
                vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
                treated.add(name)
inspectors.py 文件源码 项目:gitsome 作者: donnemartin 项目源码 文件源码 阅读 52 收藏 0 点赞 0 评论 0
def pdef(self, obj, oname=''):
        """Print the call signature for any callable object.

        If the object is a class, print the constructor information.
        """

        if not callable(obj):
            print('Object is not callable.')
            return

        header = ''

        if inspect.isclass(obj):
            header = self.__head('Class constructor information:\n')
            obj = obj.__init__
        elif (not ISPY3K) and type(obj) is types.InstanceType:
            obj = obj.__call__

        output = self._getdef(obj, oname)
        if output is None:
            self.noinfo('definition header', oname)
        else:
            print(header, output, end=' ', file=sys.stdout)
USBIP.py 文件源码 项目:PythonUSBIP 作者: Frazew 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def formatDevicesList(self, devicesCount):

        pack_format = '>'
        i = 0
        for field in self._fields_:
            if (i == devicesCount + 2):
                break
            if type(field[1]) is types.InstanceType:
                if BaseStucture in field[1].__class__.__bases__:
                    pack_format += str(field[1].size()) + 's'
            elif 'si' == field[1]:
                pack_format += 'c'
            elif '<' in field[1]:
                pack_format += field[1][1:]
            else:
                pack_format += field[1]
            i += 1
        return pack_format
USBIP.py 文件源码 项目:PythonUSBIP 作者: Frazew 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def packDevicesList(self, devicesCount):
        values = []
        i = 0
        for field in self._fields_:
            if (i == devicesCount + 2):
                break
            if type(field[1]) is types.InstanceType:
                if BaseStucture in field[1].__class__.__bases__:
                     values.append(getattr(self, field[0], 0).pack())
            else:
                if 'si' == field[1]:
                    values.append(chr(getattr(self, field[0], 0)))
                else:
                    values.append(getattr(self, field[0], 0))
            i += 1
        return struct.pack(self.formatDevicesList(devicesCount), *values)
rebuild.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def latestVersionOf(self, anObject):
        """
        Get the latest version of an object.

        This can handle just about anything callable; instances, functions,
        methods, and classes.
        """
        t = type(anObject)
        if t == types.FunctionType:
            return latestFunction(anObject)
        elif t == types.MethodType:
            if anObject.im_self is None:
                return getattr(anObject.im_class, anObject.__name__)
            else:
                return getattr(anObject.im_self, anObject.__name__)
        elif t == types.InstanceType:
            # Kick it, if it's out of date.
            getattr(anObject, 'nothing', None)
            return anObject
        elif t == types.ClassType:
            return latestClass(anObject)
        else:
            log.msg('warning returning anObject!')
            return anObject
PythonUtil.py 文件源码 项目:POTCO-PS 作者: ksmit799 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def itype(obj):
    # version of type that gives more complete information about instance types
    global dtoolSuperBase
    t = type(obj)
    if t is types.InstanceType:
        return '%s of <class %s>>' % (repr(types.InstanceType)[:-1],
                                      str(obj.__class__))
    else:
        # C++ object instances appear to be types via type()
        # check if this is a C++ object
        if dtoolSuperBase is None:
            _getDtoolSuperBase()
        if isinstance(obj, dtoolSuperBase):
            return '%s of %s>' % (repr(types.InstanceType)[:-1],
                                  str(obj.__class__))
        return t
expression_z3.py 文件源码 项目:ARMPython 作者: agustingianni 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def unwrap_args(args, kw):
    #debug!
#    c=0
#    for x in args:
#        if isinstance(x, Expr):
#            print "arg %d, EXPR: %s" % (c, str(x))
#        else:
#            if type(x) == types.InstanceType: 
#                print "arg %d, Z3: %s" %(c, x.__class__)
#            else:
#                print "arg %d, Z3: %s" %(c, type(x))
#        print traceback.print_stack()
#        c+=1
    newargs=[x.__backend__() if isinstance(x, Expr) else x for x in args]
    if isinstance(kw, dict): 
        newkw=dict(starmap(lambda k,v: (k, v if not isinstance(v, Expr) else v.__backend__()), kw.iteritems()))
    else:
        newkw=kw
    return (newargs, newkw)
MiddleObject.py 文件源码 项目:w4py 作者: Cito 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def updateReferencingListAttrs(self):
        """Update all referencing list attributes.

        Checks through all object references, and asks each referenced
        object to remove us from any list attributes that they might have.
        """
        for attr in self.klass().allAttrs():
            if isinstance(attr, ObjRefAttr):
                value = getattr(self, '_' + attr.name())
                if value is not None:
                    if isinstance(value, (MiddleObject, InstanceType)):
                        value.removeObjectFromListAttrs(self)
                    elif isinstance(value, long):
                        obj = self.store().objRefInMem(value)
                        if obj:
                            obj.removeObjectFromListAttrs(self)
visualstudio_py_debugger.py 文件源码 项目:DjangoWebProject 作者: wrkettlitz 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def collect_variables(self, vars, objects, names, treated, skip_unknown = False):
        for name in names:
            if name not in treated:
                try:
                    obj = objects[name]
                    try:
                        if sys.version[0] == '2' and type(obj) is types.InstanceType:
                            type_name = "instance (" + obj.__class__.__name__ + ")"
                        else:
                            type_name = type(obj).__name__
                    except:
                        type_name = 'unknown'
                except:
                    if skip_unknown:
                        continue
                    obj = SynthesizedValue('<undefined>', len_value=0)
                    type_name = 'unknown'
                vars.append((name, type(obj), safe_repr(obj), safe_hex_repr(obj), type_name, get_object_len(obj)))
                treated.add(name)
traitlets.py 文件源码 项目:blender 作者: gastrodia 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def error(self, obj, value):
        kind = type(value)
        if (not py3compat.PY3) and kind is InstanceType:
            msg = 'class %s' % value.__class__.__name__
        else:
            msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )

        if obj is not None:
            e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
                % (self.name, class_of(obj),
                   self.info(), msg)
        else:
            e = "The '%s' trait must be %s, but a value of %r was specified." \
                % (self.name, self.info(), msg)

        raise TraitError(e)


问题


面经


文章

微信
公众号

扫码关注公众号