[英]Will the str() method in Python work for all types of parameters?
I am trying to raise error messages using the the following line of code: 我正在尝试使用以下代码行引发错误消息:
def raise_error(value):
error = "The value " + str(value) + " does not satisfy the given conditions."
# Other stuff
The value is basically user input obtained from a JSON API, so I am trying to consider all possibilities. 该值基本上是从JSON API获得的用户输入,因此我正在尝试考虑所有可能性。 Can the method above itself cause an exception in my system if the value given cannot be turned into a string using the
str()
method? 如果给定的值无法使用
str()
方法转换为字符串,上述方法本身会在我的系统中引起异常吗? If yes, then what are such values that would create the exception? 如果是,那么将产生异常的值是什么?
The str
method will always produce an output, it just might not be meaningful. str
方法将始终产生输出,只是可能没有意义。 As noted in the docs here it's calling either __str__
or __repr__
depending on what is defined. 如此处的文档
__repr__
根据定义的内容,它调用__str__
或__repr__
。 For all of the basic types like int, float, bool, etc you'll get a nice output. 对于所有基本类型(例如int,float,bool等),您将获得不错的输出。 For a custom class though you'll probably get some garbage like:
对于自定义类,尽管您可能会得到一些垃圾,例如:
class test:
pass
print(str(test()))
>>> <__main__.test object at 0x107f2ba20>
Now if you define a __str__
method you'll get something nice like so 现在,如果您定义
__str__
方法,您将得到如下所示的漂亮内容
class test:
def __str__(self):
return "A test object"
print(str(test()))
>>> 'A test object'
Short answer: you don't have to worry about it. 简短的答案:您不必担心。 The string is generated by the
__str__
or __repr__
functions, and one or both of these will automatically be created on all new objects and primitives. 该字符串由
__str__
或__repr__
函数生成,并且将在所有新对象和基元上自动创建其中一个或两个。
But technically there are a few scenarios where developers can do dumb stuff. 但是从技术上讲,在某些情况下,开发人员可以做一些愚蠢的事情。
Scenario A) The __str__
function does not return a string: 方案A)
__str__
函数不返回字符串:
class Test():
def __str__(value):
return
raise_error(Test())
This results in the error 这导致错误
TypeError: __str__ returned non-string (type NoneType)
Scenario B) The __str__
function has the wrong amount of arguments: 方案B)
__str__
函数的参数数量错误:
class Test():
def __str__():
return 0
raise_error(Test())
This results in the error 这导致错误
TypeError: __str__() takes 0 positional arguments but 1 was given
Obviously in all three of these scenarios the fault lies with whatever developer was creating the bad __str__
functions. 显然,在所有这三种情况下,故障都在于开发人员创建了错误的
__str__
函数。 I think we can all agree that these are not cases your code should have to handle. 我认为我们都可以同意这些不是您的代码必须处理的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.