有人能解释一下为什么这两个列表不相等吗?我的意思是输出应该是真的,但它的输出是假的。为什么?
# CASE 1
list1 = []
for item in [self.home_btn, self.secret_dir_btn, self.info_btn]:
list1.append(QPropertyAnimation(item, b"size"))
# CASE 2
self.home_btn_anim = QPropertyAnimation(self.home_btn, b"size")
self.secret_dir_btn_anim = QPropertyAnimation(self.secret_dir_btn, b"size")
self.info_btn_anim = QPropertyAnimation(self.info_btn, b"size")
list2 = [self.home_btn_anim, self.secret_dir_btn_anim, self.info_btn_anim]
# Output
print(list1 == list2)
# Further code
另外,如果我使用案例1来创建列表,我的后续代码将无法正常工作。但是使用案例2创建列表可以使代码正常工作。为什么?我该怎么解决呢
首先,介绍python如何比较sequences
因此,每个元素必须等于另一个序列中对应的元素。如何检查对象的相等性?如果一个对象未实现^{} ,则该类型的两个对象之间的比较仅检查两个对象是否完全相同。与中一样,对同一对象的引用-这是
is
操作符所做的由于^{} 没有实现
__eq__
,因此只能执行is
检查。这显然会导致不同对象引用的错误如果愿意,可以扩展
QPropertyAnimation
并实现自己的__eq__
-但请注意,为动画对象实现相等可能并不理想。但是,如果您严格地希望基于这些属性的相等性用于您的用例,那么这可能很好
正如他们已经向您指出的,序列之间的比较是逐元素进行的,考虑到您试图做的是比较QPropertyAnimation
另一方面,由于设计原因,QoObject不具有可比性,因为它们处理许多内部状态,这意味着即使它们具有相同的属性,它们的行为方式也不相同。QPropertyAnimation是QObject,因此它们也继承了该限制
考虑到这一点,不建议实现
__eq__
方法,因为它与预定义的设计相矛盾,相反,如果要比较某些属性,请创建一个按属性比较属性的方法:相关问题 更多 >
编程相关推荐