The Python string comparison is, ==, __ cmp__

0, str this class, are commonly used, often can see two strings, or is performed == Comparison

and is ==
A, is represented by contrast object identifier (i.e., memory address), used to check whether the object identifiers match, i.e., whether the two objects in memory matches the address (memory address of the first byte of the object ( you often see to address either hexadecimal display, or is decimal))


B, when using the strA is strB corresponds id (strA) == id (strB), because the strings are immutable objects, so there is the concept of string pool, if the contrast is so returned True, then == It will certainly return True
 

1, represents the value == two objects are equal, the equivalent of calling __eq __ () method of the magic, i.e. strA == strB corresponds strA .__ eq __ (strB)

str rewrite __eq__ method

 

2, this time, we introduce a more magical method __cmp __ (next Python3.x already abandoned baby)

__cmp__
when a, int, str and other built-in data types ordering, Python is sorted () according to a default return value comparison function __cmp__ sort (int, str also rewritten __cmp __ (python2.x lower)
B, int , str now abandoned __cmp__ magic (python3.x lower)), abandoned after the __cmp__ method, the new definition of __eq__, __ne__, __lt__, __gt__ other new magic method


, but this Python2. knowledge should know ...... at x, the following syntax is Python2.x

However, if an instance of an object on a set of Person class need to sort, we must provide our own special way __ __cmp ():

class Person (Object) :
DEF the __init __ (Self, name, Age):
the self.name = name (http://www.amjmh.com)
self.age = Age
DEF __str __ (Self):
return '(% S:% S)'% ( the self.name, self.age)
__repr__ = __str__

DEF __cmp __ (Self, OTHER):
IF the self.name <other.name:
return -1
elif the self.name> other.name:
return. 1
the else:
return 0
Student class implements the above __cmp __ () method, __ cmp__ instance itself with self and other incoming example compares self less than if other objects, returns -1 if s is greater than the other object, it returns 1 if the two equal object, it returns 0.

In order to enhance the understanding here is assumed to digital will better understand the intention -1,1,0, and you think about it?

Person class implements sorting by name:

>>> L = [Person ( 'Tim', 25), Person ( 'Bob', 30), Person ( 'Alice', 23 is)]
>>> Print the sorted (L)
[(Alice: 23), ( Bob: 30), (Tim: 25)]

for comparison string and compares characters in the ASCII code obviously comparisons made in accordance with the ASCII code of the first character
Note: If the list It includes not only the elements in the Person object class, __cmp__ being given:

L = [Person ( 'Tim', 25), Student ( 'Bob', 30, 100, 'the Hello']
------- --------------

Guess you like

Origin www.cnblogs.com/liyanyan665/p/11322922.html