我有一个方法get_annotated_pkt_msg()
它采用布尔参数show_timestamp
。我希望这是一个可选参数,因此如果调用者未指定参数,它将默认为在用户定义的配置中设置的参数。此配置存储在容器已传入通过构造函数依赖注入self.config
:为什么我不能将可选的paremeter默认为成员变量?
class XcpDaqFrame(XcpFrame):
def __init__(self, *args, **kwargs):
# Pass init arguments to super-class.
super(XcpDaqFrame, self).__init__(*args, **kwargs)
# Passed by dependency injection to this constructor.
self.config = config
def get_annotated_pkt_msg(
self,
show_timestamp=self.config.getConfigItem('display.packet_time')):
##### SyntaxError here^(on the dot after 'self') ########
"""Return the annotated packet message
:param bool show_timestamp:
:rtype: str
"""
# Optionally, show the timestamp of the packet.
if show_timestamp:
timestamp = get_timestamp()
timestamp_msg = u", Timestamp: {} μs".format(timestamp)
else:
timestamp_msg = ""
return timestamp_msg
frame = XcpDaqFrame(my_config)
frame.get_annotated_pkt_msg()
如果我尝试在它上面告诉我,上面标线:
SyntaxError: invalid syntax
为什么我可以通过self
方法,但不能通过它们self.config
?
'自我'未定义。你应该使用'None'作为默认值,然后将它设置为你想要的值,如果它真的是'None'。 –
@HaazuoGao尽管在第一个参数中定义了自我* IS *,这很奇怪。感谢您的解决方法,我只是认为它会更明确地说明值来自方法标题的位置。 – DBedrenko
默认参数在调用时不进行评估,但在**定义**处进行评估。 '自我'在定义时没有价值,所以它不会那样工作。 –