[英]How to make it so if any variable in a list is greater than an integer, it will print out something, else it will print out something else?
[英]How do you statically type a variable so it only takes an integer greater than 0
我想要做的是创建一个名为Pizza
的类,它接受 2 个输入: self
和radius
如果您创建Pizza
的实例,您在其中输入任何radius
而不是大于 0 的整数,它将打印一条语句: 'Sorry, but that is an invalid input. A valid input is any integer greater than 0.'
'Sorry, but that is an invalid input. A valid input is any integer greater than 0.'
到目前为止,这是我的Pizza
课程,但我想进行更改,以便上述内容正确:
class Pizza:
def __init__(self, radius):
self.radius = radius
利用Python 的错误和异常处理可能是一种更灵活的方法。
不是在类定义中硬编码错误响应(即打印出错误字符串),而是通知调用者发生了错误条件,然后可以对该上下文进行适当的操作(即在控制台,生成图形错误提示,忽略错误,尝试不同的输入等)。
class Pizza:
def __init__(self, radius):
if not isinstance(radius, int):
raise ValueError('radius must be an integer')
if not radius > 0:
raise ValueError('radius must be greater than 0')
self.radius = radius
inputs = [8, -8, 8.8, '8', 'foo']
print('\nTesting inputs and outputting error messages:')
for r in inputs:
print('r: {} ({})'.format(r, type(r)))
try:
p = Pizza(r)
except ValueError as e:
print('Unable to create Pizza: {}'.format(e))
continue
print('p.radius: {}'.format(p.radius))
print('\nTesting inputs and silently discarding errors:')
for r in inputs:
print('r: {} ({})'.format(r, type(r)))
try:
p = Pizza(r)
except ValueError as e:
continue
print('p.radius: {}'.format(p.radius))
输出
$ python3 pizza.py
Testing inputs and outputting error messages:
r: 8 (<class 'int'>)
p.radius: 8
r: -8 (<class 'int'>)
Unable to create Pizza: radius must be greater than 0
r: 8.8 (<class 'float'>)
Unable to create Pizza: radius must be an integer
r: 8 (<class 'str'>)
Unable to create Pizza: radius must be an integer
r: foo (<class 'str'>)
Unable to create Pizza: radius must be an integer
Testing inputs and silently discarding errors:
r: 8 (<class 'int'>)
p.radius: 8
r: -8 (<class 'int'>)
r: 8.8 (<class 'float'>)
r: 8 (<class 'str'>)
r: foo (<class 'str'>)
这可以通过
class Pizza:
def __init__(self, radius):
if isinstance(radius, int) and radius > 0 :
self.radius = radius
else:
print('Sorry, but that is an invalid input. A valid input is any integer greater than 0.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.