2015-09-25 32 views
1

我有一个方法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

+1

'自我'未定义。你应该使用'None'作为默认值,然后将它设置为你想要的值,如果它真的是'None'。 –

+0

@HaazuoGao尽管在第一个参数中定义了自我* IS *,这很奇怪。感谢您的解决方法,我只是认为它会更明确地说明值来自方法标题的位置。 – DBedrenko

+2

默认参数在调用时不进行评估,但在**定义**处进行评估。 '自我'在定义时没有价值,所以它不会那样工作。 –

回答

3

一个函数的默认参数进行评估时,函数定义,而不是函数被调用,所以在函数的定义(自没有值),而不能使用其它参数相同的时间功能默认参数。这也导致其他陷阱像可变的默认参数(了解更多关于here)。

取而代之的是,您可以尝试使用其他一些默认值(如None)左右,然后将其默认为self.config.getConfigItem('display.packet_time')(如果它的None)。示例 -

def get_annotated_pkt_msg(
     self, 
     show_timestamp=None): 
    ##### SyntaxError here^(on the dot after 'self') ######## 
    """Return the annotated packet message 

    :param bool show_timestamp: 
    :rtype: str 
    """ 
    if show_timestamp is None: 
     show_timestamp = self.config.getConfigItem('display.packet_time') 
    # Optionally, show the timestamp of the packet. 
    ... #Rest of the logic 
+0

谢谢你的解释和有趣的链接:) – DBedrenko

相关问题