[英]Using __repr__ when parameter defaults to None, but may be a str
I have a class that can be initializes with several parameters. 我有一个可以用几个参数初始化的类。 Some of these parameters have default values of
None
, but if a value is provided it should be str
. 其中一些参数的默认值为
None
,但是如果提供了值,则应为str
。 I would like to have a nice pythonic output from __repr()__
, but can't figure out how to handle None
as well as a possible str
in one return statement. 我想从
__repr()__
获得一个不错的__repr()__
输出,但无法弄清楚如何处理None
以及在一个return语句中可能的str
。 I would like to avoid having various return statements depending on whether a parameter is None
or a str
value. 我想避免根据参数是
None
还是str
值使用各种return语句。
A basic example: 一个基本的例子:
class Demo:
"""Demo of how not to deal with None in __repr()__"""
def __init__(self, w:int, x:int, y=None, z=None):
self.w = w
self.x = x
self.y = y
self.z = z
def __repr__(self):
return f"demo(w={self.w}, x={self.x}, y='{self.y}', z='{self.z}')"
Here are two examples of using this class: 这是使用此类的两个示例:
>>> d1 = Demo(5, 4)
>>> d1
Demo(w=5, x=4, y='None', z='None')
>>> d2 = Demo(5, 4, 'me', 'you')
>>> d2
Demo(w=5, x=4, y='me', z='you')
Note how None
is in single quotes, which is not what I want. 请注意,单引号中
None
,这不是我想要的。 But me
and you
are in quotes, which is appropriate given that they are str
. 但是
me
和you
用引号引起来,考虑到它们是str
,这是适当的。
use repr
in your __repr__
function 在
__repr__
函数中使用repr
def __repr__(self):
return f"demo(w={self.w}, x={self.x}, y={repr(self.y)}, z={repr(self.z)})"
test: 测试:
d = Demo(23,12,y='hello')
print(d)
demo(w=23, x=12, y='hello', z=None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.