当前位置:
文档之家› Python英文PPT课件:10-Equality
Python英文PPT课件:10-Equality
numbers and alias refer to the same object in memory
numbers and copy refer to distinct objects whose contents are the same
8
Identity vs Structural Equivalence
numbers = Array(4) alias = numbers
# Then put 3, 2, 6, and 4 in there # An alias
numbers alias
3264 0123
numbers and alias refer to the same object in memory
• Thus,
>>> "Hi" == "hi" False >>> "Hi".__eq__("hi") False >>>
Fundamentals of Python: Data Structures
2
Python’s Two Equality Operators
• The is operator tests two objects for identity (same address in memory)
>>> numbers == alias True >>> numbers is alias True >>> numbers is copy False >>> numbers == copy False
# Counterintuitive: why not True?
numbers and alias refer
numbers and alias refer to the same object in memory
numbers and copy refer to distinct objects whose contents are the same
9
Identity vs Structural Equivalence
numbers and copy refer to distinct objects whose contents are the same
6
Identity vs Structural Equivalence
>>> numbers == alias True
numbers alias
3264 0123
7
Identity vs Structural Equivalence
>>> numbers == alias True >>> numbers is alias True
numbers alias
3264 0123
copy
3264
0123
Fundamentals of Python: Data Structures
Fundamentals of Python Data Structures
What Is Equality?
What Is Equality?
• For collections, the == operator is syntactic sugar for a call of the __eq__ method on the left operand, with the right operand as an argument (see Section 8.3.4 of the book)
copy = resize(numbers, 1)
# A real copy
numbers alias
3264 0123
copy
3264
0123
Fundamentals of Python: Data Structures
numbers and alias refer to the same object in memory
• The == operator has a default implementation (__eq__ method) in the object class
• This implementation uses is
Fundamentals of Python: Data Structures
>>> numbers == alias True >>> numbers is alias True >>> numbers is copy False
numbers alias
3264 0123
copy
3264
0123
Fundamentals of Python: Data Structures
numbers alias
3264 0123
to the same object in memory
copy
3264
0123
Fundamentals of Python: Data Structures
numbers and copy refer to distinct objects whose contents are the same
Fundamentals of Python: Data Structures
5
Identity vs Structural Equivalence
numbers = Array(4)
# Then put 3, 2, 6, and 4 in there
alias = numbers
Hale Waihona Puke # An aliascopy
3264
0123
Fundamentals of Python: Data Structures
numbers and alias refer to the same object in memory
numbers and copy refer to distinct objects whose contents are the same
3
Identity vs Structural Equivalence
numbers = Array(4)
# Then put 3, 2, 6, and 4 in there
numbers
3264 0123
Fundamentals of Python: Data Structures
4
Identity vs Structural Equivalence