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


Python id函数代码示例

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


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

示例1: __and__

 def __and__(self,other_tester):
     ids1 = dict([(id(r),r) for r in self.records])
     ids2 = dict([(id(r),r) for r in other_tester.records])
     ids = set(ids1.keys()) & set(ids2.keys())
     res = Tester(self.db,self.key)
     res.records = [ids1[_id] for _id in ids]
     return res
开发者ID:1901,项目名称:sublime_sync,代码行数:7,代码来源:PyDbLite.py

示例2: dump_transitions

 def dump_transitions(self, state, file):
   chars_leading_to_state = {}
   special_to_state = {}
   for (c, s) in state.iteritems():
     if len(c) == 1:
       chars = chars_leading_to_state.get(id(s), None)
       if chars is None:
         chars = []
         chars_leading_to_state[id(s)] = chars
       chars.append(c)
     elif len(c) <= 4:
       special_to_state[c] = s
   ranges_to_state = {}
   for state in self.states:
     char_list = chars_leading_to_state.get(id(state), None)
     if char_list:
       ranges = self.chars_to_ranges(char_list)
       ranges_to_state[ranges] = state
   ranges_list = ranges_to_state.keys()
   ranges_list.sort()
   for ranges in ranges_list:
     key = self.ranges_to_string(ranges)
     state = ranges_to_state[ranges]
     file.write("      %s --> State %d\n" % (key, state['number']))
   for key in ('bol', 'eol', 'eof', 'else'):
     state = special_to_state.get(key, None)
     if state:
       file.write("      %s --> State %d\n" % (key, state['number']))
开发者ID:shalstvedt,项目名称:ccv-revival,代码行数:28,代码来源:Machines.py

示例3: _handle_edge_constraint

 def _handle_edge_constraint(
         constraint, json_constraints_dictory_rep, edge):
     if isinstance(constraint, AbstractKeyAllocatorConstraint):
         if isinstance(constraint,
                       KeyAllocatorContiguousRangeContraint):
             key_constraint = dict()
             key_constraint['type'] = "reserve_resource"
             key_constraint['edge'] = str(id(edge))
             key_constraint['resource'] = "keys"
             key_constraint['restriction'] = "continious_range"
             json_constraints_dictory_rep.append(key_constraint)
         if isinstance(constraint,
                       KeyAllocatorFixedKeyAndMaskConstraint):
             key_constraint = dict()
             key_constraint['type'] = "reserve_resource"
             key_constraint['edge'] = str(id(edge))
             key_constraint['resource'] = "keys"
             key_constraint['restriction'] = "[key, mask]"
             constraint_string = "["
             for key_and_mask in constraint.keys_and_masks:
                 constraint_string += "[{}, {}]"\
                     .format(key_and_mask.key, key_and_mask.mask)
             constraint_string += "]"
             key_constraint['key'] = constraint_string
             json_constraints_dictory_rep.append(key_constraint)
         if isinstance(constraint,
                       KeyAllocatorFixedMaskConstraint):
             key_constraint = dict()
             key_constraint['type'] = "reserve_resource"
             key_constraint['edge'] = str(id(edge))
             key_constraint['resource'] = "keys"
             key_constraint['restriction'] = "[mask]"
             key_constraint['mask'] = constraint.mask
             json_constraints_dictory_rep.append(key_constraint)
开发者ID:tophensen,项目名称:PACMAN,代码行数:34,代码来源:create_file_constraints.py

示例4: addpage

    def addpage(self, page):
        self._trailer = None
        if page.Type != PdfName.Page:
            raise PdfOutputError('Bad /Type:  Expected %s, found %s'
                                 % (PdfName.Page, page.Type))
        inheritable = page.inheritable  # searches for resources
        newpage = IndirectPdfDict(
            page,
            Resources=inheritable.Resources,
            MediaBox=inheritable.MediaBox,
            CropBox=inheritable.CropBox,
            Rotate=inheritable.Rotate,
        )
        self.pagearray.append(newpage)
        self.pagemap[id(page)] = newpage

        # Add parents in the hierarchy to objects we
        # don't want to output
        killobj = self.killobj
        obj = page.Parent
        while obj is not None:
            objid = id(obj)
            if objid in killobj:
                break
            killobj[objid] = obj
            obj = obj.Parent
        return self
开发者ID:abrasive,项目名称:pdfrw,代码行数:27,代码来源:pdfwriter.py

示例5: test_sort_index_inplace

    def test_sort_index_inplace(self):
        frame = DataFrame(np.random.randn(4, 4), index=[1, 2, 3, 4],
                          columns=['A', 'B', 'C', 'D'])

        # axis=0
        unordered = frame.ix[[3, 2, 4, 1]]
        a_id = id(unordered['A'])
        df = unordered.copy()
        df.sort_index(inplace=True)
        expected = frame
        assert_frame_equal(df, expected)
        self.assertNotEqual(a_id, id(df['A']))

        df = unordered.copy()
        df.sort_index(ascending=False, inplace=True)
        expected = frame[::-1]
        assert_frame_equal(df, expected)

        # axis=1
        unordered = frame.ix[:, ['D', 'B', 'C', 'A']]
        df = unordered.copy()
        df.sort_index(axis=1, inplace=True)
        expected = frame
        assert_frame_equal(df, expected)

        df = unordered.copy()
        df.sort_index(axis=1, ascending=False, inplace=True)
        expected = frame.ix[:, ::-1]
        assert_frame_equal(df, expected)
开发者ID:AlexisMignon,项目名称:pandas,代码行数:29,代码来源:test_sorting.py

示例6: simplify

def simplify(axioms):
    """Remove duplicate axioms, duplicates within axioms, and dominated axioms."""

    # Remove duplicates from axiom conditions.
    for axiom in axioms:
        axiom.condition.sort()
        remove_duplicates(axiom.condition)

    # Remove dominated axioms.
    axioms_by_literal = {}
    for axiom in axioms:
        for literal in axiom.condition:
            axioms_by_literal.setdefault(literal, set()).add(id(axiom))

    axioms_to_skip = set()
    for axiom in axioms:
        if id(axiom) in axioms_to_skip:
            continue   # Required to keep one of multiple identical axioms.
        if not axiom.condition: # empty condition: dominates everything
            return [axiom]
        literals = iter(axiom.condition)
        dominated_axioms = axioms_by_literal[next(literals)]
        for literal in literals:
            dominated_axioms &= axioms_by_literal[literal]
        for dominated_axiom in dominated_axioms:
            if dominated_axiom != id(axiom):
                axioms_to_skip.add(dominated_axiom)
    return [axiom for axiom in axioms if id(axiom) not in axioms_to_skip]
开发者ID:ipa-fmw-ce,项目名称:cob_automated_planning,代码行数:28,代码来源:axiom_rules.py

示例7: set_subservice

    def set_subservice(self, obj):
        """Add a sub-service object.

        :param obj: stackinabox.services.StackInABoxService instance
        :raises: RouteAlreadyRegisteredError if the route is already registered
        :returns: n/a
        """
        # ensure there is not already a sub-service
        if self.obj is not None:
            raise RouteAlreadyRegisteredError(
                'Service Router ({0} - {1}): Route {2} already has a '
                'sub-service handler'
                .format(id(self), self.service_name, self.uri))

        # warn if any methods are already registered
        if len(self.methods):
            logger.debug(
                'WARNING: Service Router ({0} - {1}): Methods detected '
                'on Route {2}. Sub-Service {3} may be hidden.'
                .format(id(self), self.service_name, self.uri, obj.name))

        # Ensure we do not have any circular references
        assert(obj != self.parent_obj)

        # if no errors, save the object and update the URI
        self.obj = obj
        self.obj.base_url = '{0}/{1}'.format(self.uri, self.service_name)
开发者ID:BenjamenMeyer,项目名称:stackInABox,代码行数:27,代码来源:service.py

示例8: _find_reference_cycle

    def _find_reference_cycle(self):
        # Shorthand variables, useful if attached with PDB.
        # g = "unfetchable objects"
        # i2o = "id to object, for objects in `g`"
        # gr = "get referrers of an object in the unfetchable objects"
        # gri = "get the id of the above referrers"
        g = gc.garbage
        i2o = {id(o): o for o in g}
        gr = lambda o: [r for r in gc.get_referrers(o) if id(r) in i2o]
        gri = lambda o: [id(r) for r in gr(o)]
        
        # Find a loop by walking unfetched objects, stepping to an arbitrary
        # referrer each time. When an object that has already been encountered
        # is encountered again a loop has been found.
        #
        # The loop is described in terms of object ids, to avoid having to
        # invoke objects' __eq__ method.
        def find_loop(start_idx=0):
            path = [id(g[start_idx])]
            while True:
                path.append(gri(i2o[path[-1]])[0])
                # This check could be made more efficient using a set to track
                # elements in `path`.
                if path[-1] in path[:-1]:
                    return path[path.index(path[-1]):]

        loop = find_loop()
        logger.error("Reference cycle of size {} found:".format(len(loop) - 1))
        for obj_id in loop:
            logger.error("    {!r} (id: {})".format(i2o[obj_id], obj_id))

        if _DEBUG_REFERENCE_CYCLES:
            loop = [i2o[o] for o in loop]
            import pdb
            pdb.set_trace()
开发者ID:cisco,项目名称:xr-telemetry-m2m-lib,代码行数:35,代码来源:_utils.py

示例9: __repr__

 def __repr__(self):
     if self.cdn:
         return '<RH cdn Repo: {0} within distro:{1}, object: {2}>'.format(
             self.data['repository'], self.distro, hex(id(self)))
     else:
         return '<RH custom Repo url: {0} object: {1}>'.format(
             self.url, hex(id(self)))
开发者ID:sghai,项目名称:robottelo,代码行数:7,代码来源:products.py

示例10: testBasicD

    def testBasicD(self):
        from music21 import stream, note, converter, spanner
        import copy

        s = stream.Stream()
        n1 = note.Note('d2', quarterLength=2.0)
        n2 = note.Note('e2', quarterLength=2.0)
        sp = spanner.Slur(n1, n2)

        s.append(n1)
        s.append(n2)
        s.append(sp)

        # the deepcopy is what creates the bug in the preservation of a weakref

        #temp = converter.freezeStr(s)

        sCopy = copy.deepcopy(s)
        temp = converter.freezeStr(sCopy)

        post = converter.thawStr(temp)
        self.assertEqual(len(post.notes), 2)
        self.assertEqual(str(post.notes[0].pitch), 'D2')
        spPost = post.spanners[0]
        self.assertEqual(spPost.getSpannedElements(), [post.notes[0], post.notes[1]])
        self.assertEqual(spPost.getSpannedElementIds(), [id(post.notes[0]), id(post.notes[1])])
开发者ID:cuthbertLab,项目名称:music21,代码行数:26,代码来源:testSerialization.py

示例11: test_constructor

    def test_constructor(self):
        assert self.ts.index.is_all_dates

        # Pass in Series
        derived = Series(self.ts)
        assert derived.index.is_all_dates

        assert tm.equalContents(derived.index, self.ts.index)
        # Ensure new index is not created
        assert id(self.ts.index) == id(derived.index)

        # Mixed type Series
        mixed = Series(['hello', np.NaN], index=[0, 1])
        assert mixed.dtype == np.object_
        assert mixed[1] is np.NaN

        assert not self.empty.index.is_all_dates
        assert not Series({}).index.is_all_dates
        pytest.raises(Exception, Series, np.random.randn(3, 3),
                      index=np.arange(3))

        mixed.name = 'Series'
        rs = Series(mixed).name
        xp = 'Series'
        assert rs == xp

        # raise on MultiIndex GH4187
        m = MultiIndex.from_arrays([[1, 2], [3, 4]])
        pytest.raises(NotImplementedError, Series, m)
开发者ID:BobMcFry,项目名称:pandas,代码行数:29,代码来源:test_constructors.py

示例12: updateLEDTable

 def updateLEDTable(self, current=None):
     self.LEDtable.clear()
     self.LEDtable.setRowCount(len(self.LED_LIST))
     self.LEDtable.setColumnCount(3)
     self.LEDtable.setHorizontalHeaderLabels(["Wavelength (nm)", "Amplitude (mW)", "   Duty Cycle   "])
     self.LEDtable.setEditTriggers(QTableWidget.NoEditTriggers) # Don't allow edits
     self.LEDtable.setSelectionBehavior(QTableWidget.SelectRows) # Select whole row
     self.LEDtable.setSelectionMode(QTableWidget.SingleSelection) # Select one row at a time
     selected = None
     self.points.sort()
     for row, (wavelength, amplitude, dummy1, dummy2) in enumerate(self.LED_LIST):
         item = QTableWidgetItem("%d" % wavelength)
         item.setTextAlignment(Qt.AlignCenter)
         if current is not None and current == id(row):
             selected = item
         item.setData(Qt.UserRole, QVariant(long(id(row))))
         self.LEDtable.setItem(row, 0, item) #void setItem ( int row, int column, QTableWidgetItem * item )
         if row < len(self.led_outputs):
             item = QTableWidgetItem("%.2f" % self.led_outputs[row])
             item.setTextAlignment(Qt.AlignCenter)
             self.LEDtable.setItem(row, 1, item)
             item = QTableWidgetItem("%.3f" % (self.led_outputs[row]/amplitude))
             item.setTextAlignment(Qt.AlignCenter)
             self.LEDtable.setItem(row, 2, item)
     self.LEDtable.resizeColumnsToContents()
     if selected is not None:
         selected.setSelected(True)
         self.LEDtable.setCurrentItem(selected)
         self.LEDtable.scrollToItem(selected)
开发者ID:ncanac,项目名称:fcugui,代码行数:29,代码来源:FCUGUI.py

示例13: append

 def append(self, client):
     # TODO make this much more clever... we just need to loop to the 
     # right point 
     list.append(self, client)
     print id(self), "append", self
     self.x_sort()
     self.update_x_stack()
开发者ID:samurai-x,项目名称:samurai-x,代码行数:7,代码来源:__init__.py

示例14: test_same_sets_in_lists_same_hash

    def test_same_sets_in_lists_same_hash(self):
        t1 = ["a", {1, 3, 2}]
        t2 = [{2, 3, 1}, "a"]
        t1_hash = DeepHash(t1)
        t2_hash = DeepHash(t2)

        self.assertEqual(t1_hash[id(t1)], t2_hash[id(t2)])
开发者ID:victorhahncastell,项目名称:deepdiff,代码行数:7,代码来源:test_hash.py

示例15: _substitute

    def _substitute(self, tree, nodes, node_stack):
        '''
        Let (parent(tree), parent(parent(tree)), ..., parent(...(parent(tree))...))
        the parental hierarchy of tree. It can be denoted as (P1, ..., P(n)) where P(i) is
        the node id of the i-th grandparent of tree.

        The substitution algorithm seeks for P(i) with repl_id == P(i). If found it
        replaces P(i) in P(i+1) with nodes = (N1, ..., N(k)). It is guaranteed that the node
        id of N(j) is repl_id.
        '''
        repl_id = nodes[0][0]
        if tree[0] == repl_id:
            return (tree, node_stack)
        if is_token(repl_id):          # replace token
            if is_token(tree[0]):
                tree[:] = nodes[0]
                return (tree, node_stack)
        else:
            i = len(node_stack)-1
            while i>=0:
                P = node_stack[i]
                i-=1
                if repl_id == P[0]:
                    try:
                        nd_list = node_stack[i]
                        i-=1
                        for j, N in enumerate(nd_list):
                            if id(N) == id(P):
                                nd_list[:] = nd_list[:j]+list(nodes)+nd_list[j+1:]
                                return (nd_list, node_stack[i-1:])
                    except IndexError:    # nothing to pop from node_stack
                        P[:] = nodes[0]
                        return (P, node_stack[i-1:])
        self._create_translation_error(tree, nodes, node_stack)
开发者ID:leomauro,项目名称:langscape,代码行数:34,代码来源:transformer.py


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