gpt4 book ai didi

python - __init__ 中的类参数测试

转载 作者:行者123 更新时间:2023-11-28 22:02:20 24 4
gpt4 key购买 nike

我有一个 Point 类,它接受位置、值和标志作为参数。这个类应该只接受整数作为位置和值参数。我尝试了下面的代码,但它不能正常工作。

class PointException(Exception):
pass

class Point():
def __init__(self, position, value, flag=False):
try:
if all([isinstance(x, int) for x in position, value]):
self.position = position
self.value = value
self.point = (position, value)
self.flag = flag
except:
raise PointException("Foo value and position must be integers.")

def __repr__(self):
return "< {0}, {1}, {2} >".format(self.position, self.value, self.flag)

def __eq__(self, other):
if not isinstance(other, Point):
return False
try:
return all([self.point == other.point, self.flag == other.flag])
except AttributeError:
return False

def __ne__(self, other):
return not self.__eq__(other)

更新

例如,当我尝试 Point(1, 1.2) 时,我得到一个 AttributError

AttributeError: Point instance has no attribute 'position'

最佳答案

if all([isinstance(x, int) for x in position, value])

应该是

if all(isinstance(x, int) for x in (position, value))

更一般地说,你必须在 __init__引发异常,而不是用 except 捕获它:

def __init__(self, position, value, flag=False):
if not all(isinstance(x, int) for x in (position, value)):
raise PointException("Foo value and position must be integers.")

self.position = position
self.value = value
self.point = (position, value)
self.flag = flag

您可以在其他答案中了解其他方面的改进

关于python - __init__ 中的类参数测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11450646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com