gpt4 book ai didi

python - 类的数据属性应该如何用作类方法中的默认参数?

转载 作者:行者123 更新时间:2023-11-28 19:55:29 25 4
gpt4 key购买 nike

假设我想将类的方法参数的默认值设置为类的某些数据属性的值。这样做的合适方法是什么?有没有办法使用 lambda 函数来做到这一点?

下面是一些示例代码:

class A(object):

def __init__(
self
):
self._defaultReportText = "hello world"

def report(
self,
text = self._defaultReportText
):
return(text)

显然,report 方法的参数 text 的默认值规范在这里不起作用,因为此时未定义 self .我应该如何使这个值可用?

最佳答案

如果我理解你的问题,我通常会这样做:

def report(self, text = None):
if text is None:
text = self._defaultReportText
return(text)

(编辑:根据 Warren Weckesser 的建议,将 if not text 更改为 if text is None。)

关于python - 类的数据属性应该如何用作类方法中的默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27673137/

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