为了使我的代码与PyQt5/6和PySide2/6兼容,我写道:
if not hasattr(QtCore.QDateTime, 'toPython'): # fix for PyQt5/6
QtCore.QDateTime.toPython = QtCore.QDateTime.toPyDateTime
使用PyQt5或PyQt6运行,这会导致
TypeError: toPyDateTime(self): first argument of unbound method must have type 'QDateTime'
调用函数时:
QtCore.QDateTime.currentDateTime().toPython()
但如果我把电话换成
QtCore.QDateTime.toPython(QtCore.QDateTime.currentDateTime())
没有错误.
但是,当我将第一段代码更改为
if not hasattr(QtCore.QDateTime, 'toPython'): # fix for PyQt5/6
QtCore.QDateTime.toPython = lambda self: QtCore.QDateTime.toPyDateTime(self)
不管我怎么叫toPython
函数,一切都很好.为什么我需要lambda表达式呢?
Added.为了解释我预期的行为,这里有一段简单的代码:
class A:
def __init__(self) -> None:
print(f'make A ({hex(id(self))})')
def foo(self) -> None:
print(f'A ({hex(id(self))}) foo')
class B:
def __init__(self) -> None:
print(f'make B ({hex(id(self))})')
B.bar = A.foo
b: B = B() # prints “make B (0x7efc04c67f10)” (or another id)
B.bar(b) # prints “A (0x7efc04c67f10) foo” (same id, no error)
b.bar() # same result as before, no error
相反,以下代码不起作用:
from PyQt6.QtCore import QDateTime
QDateTime.toPython = QDateTime.toPyDateTime
t: QDateTime = QDateTime.currentDateTime()
QDateTime.toPython(t) # no error
t.toPython() # raises TypeError