运算符重载:比较对象

Python 面向对象编程入门

George Boorman

Curriculum Manager, DataCamp

对象相等性

class Customer:
    def __init__(self, name, balance):
        self.name, self.balance = name, balance  

customer1 = Customer("Maryam Azar", 3000)
customer2 = Customer("Maryam Azar", 3000)

# Check for equality customer1 == customer2
False
Python 面向对象编程入门

对象相等性

class Customer:
    def __init__(self, name, balance, acc_id):
        self.name, self.balance = name, balance
        self.acc_id = acc_id    

customer1 = Customer("Maryam Azar", 3000, 123)
customer2 = Customer("Maryam Azar", 3000, 123)

customer1 == customer2
False
Python 面向对象编程入门

变量是引用

customer_one = Customer("Maryam Azar", 3000, 123)
customer_two = Customer("Maryam Azar", 3000, 123)

print(customer_one)
<__main__.Customer at 0x1f8598e2e48>
print(customer_two)
<__main__.Customer at 0x1f8598e2240>
  • print() 的输出指的是变量所分配的内存块
  • == 比较的是引用,而非数据
Python 面向对象编程入门

自定义比较

# Two different lists containing the same data
list_one = [1,2,3]
list_two = [1,2,3]

list_one == list_two
True
Python 面向对象编程入门

__eq__() 方法

  • 使用 == 比较类的两个对象时会调用 __eq__()
  • 接受两个参数:selfother,即要比较的对象
  • 返回布尔值
Python 面向对象编程入门

__eq__() 方法

class Customer:
    def __init__(self, acc_id, name):
        self.acc_id, self.name = acc_id, name

# Will be called when == is used def __eq__(self, other):
# Printout print("__eq__() is called") # Returns True if all attributes match return (self.acc_id == other.acc_id) and (self.name == other.name)
Python 面向对象编程入门

对象比较

# Two equal objects
customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(123, "Maryam Azar")

customer1 == customer2
__eq__() is called
True
# Two unequal objects - different ids
customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(456, "Maryam Azar")

customer1 == customer2
__eq__() is called
False
Python 面向对象编程入门

类型检查

  • 如果两个不同类的对象具有相同的属性和值会怎样?
    • Python 会将它们视为相等
class Customer:
    def __init__(self, acc_id, name):
        self.acc_id, self.name = idacc_id name

    def __eq__(self, other):
        # Returns True if the objects have the same attributes
        # and are of the same type
        return (self.acc_id == other.acc_id) and (self.name == other.name)\
            and (type(self) == type(other))
Python 面向对象编程入门

其他比较运算符

运算符 方法
== __eq__()
!= __ne__()
>= __ge__()
<= __le__()
> __gt__()
< __lt__()
  • 在类中自定义这些方法
Python 面向对象编程入门

Passons à la pratique !

Python 面向对象编程入门

Preparing Video For Download...