【发布时间】:2020-04-05 19:13:38
【问题描述】:
我在 Python 3 中有一个这样的类:
from typing import List
from functools import cmp_to_key
class Solution:
def __init__(self, name, age):
self.name = name
self.age = age
def cmp(self, v1: int, v2: int) -> int:
if (v1 < v2):
return -1
elif (v1 == v2):
return 0
elif (v1 > v2):
return 1
def moveZeroes(self, nums: List[int]) -> None:
nums.sort(key = cmp_to_key(cmp))
我喜欢这样调用moveZeros 方法:
p1 = Solution("John", 36)
nums = [0,7, 2, 3, 4, 5,0,9]
p1.moveZeroes(nums);
print(nums)
得到这个错误:
name 'cmp' is not defined
Stack trace:
> File "E:\LeetcodePython\LeetcodePython\Solution.py", line 20, in moveZeroes
> nums.sort(key = cmp_to_key(cmp))
> File "E:\LeetcodePython\LeetcodePython\Solution.py", line 28, in <module>
> p1.moveZeroes(nums);
Loaded '__main__'
Loaded 'runpy'
Traceback (most recent call last):
File "C:\Python38\lib\runpy.py", line 193, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Python38\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy\__main__.py", line 45, in <module>
cli.main()
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 361, in main
run()
File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 203, in run_file
The thread 'MainThread' (0x1) has exited with code 0 (0x0).
runpy.run_path(options.target, run_name="__main__")
File "C:\Python38\lib\runpy.py", line 263, in run_path
return _run_module_code(code, init_globals, run_name,
File "C:\Python38\lib\runpy.py", line 96, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "C:\Python38\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "E:\LeetcodePython\LeetcodePython\Solution.py", line 28, in <module>
p1.moveZeroes(nums);
File "E:\LeetcodePython\LeetcodePython\Solution.py", line 20, in moveZeroes
nums.sort(key = cmp_to_key(cmp))
NameError: name 'cmp' is not defined
The program 'python.exe' has exited with code 1 (0x1).
但是,如果我只是将cmp 函数移出类,就完美找到了:
from typing import List
from functools import cmp_to_key
def cmp(v1: int, v2: int) -> int:
if (v1 < v2):
return -1
elif (v1 == v2):
return 0
elif (v1 > v2):
return 1
class Solution:
def __init__(self, name, age):
self.name = name
self.age = age
def moveZeroes(self, nums: List[int]) -> None:
nums.sort(key = cmp_to_key(cmp))
########################################################################
p1 = Solution("John", 36)
nums = [0,7, 2, 3, 4, 5,0,9]
p1.moveZeroes(nums);
print(nums)
但我喜欢在类中包含比较函数,这样代码可能更易于维护。
python 3有什么办法吗?
【问题讨论】:
-
你可以使用
cmp_to_key(self.cmp)
标签: python python-3.x function class