Using self.xxxx as a default parameter - Python

前端 未结 3 690
失恋的感觉
失恋的感觉 2020-11-27 19:54

I\'m trying to simplify one of my homework problems and make the code a little better. What I\'m working with is a binary search tree. Right now I have a function in my

相关标签:
3条回答
  • 2020-11-27 20:18

    larsmans answered your first question

    For your second question, can you simply look before you leap to avoid recursion?

    def makeList(self, aNode=None):
        if aNode is None:
            aNode = self.root
        treeaslist = [aNode.data]
        if aNode.lChild:
            treeaslist.extend(self.makeList(aNode.lChild))
        if aNode.rChild:
            treeaslist.extend(self.makeList(aNode.rChild))
        return treeaslist
    
    0 讨论(0)
  • 2020-11-27 20:26

    If you want to treat None as a valid argument, you could use a **kwarg parameter.

    def function(arg1, arg2, **kwargs):
        kwargs.setdefault('arg3', default)
        arg3 = kwargs['arg3']
    
        # Continue with function
    
    function("amazing", "fantastic") # uses default
    function("foo", "bar", arg3=None) # Not default, but None
    function("hello", "world", arg3="!!!")
    
    0 讨论(0)
  • 2020-11-27 20:29

    It doesn't work because default arguments are evaluated at function definition time, not at call time:

    def f(lst = []):
        lst.append(1)
        return lst
    
    print(f()) # prints [1]
    print(f()) # prints [1, 1]
    

    The common strategy is to use a None default parameter. If None is a valid value, use a singleton sentinel:

    NOTHING = object()
    
    def f(arg = NOTHING):
        if arg is NOTHING:
            # no argument
        # etc.
    
    0 讨论(0)
提交回复
热议问题