In Python, what does dict.pop(a,b) mean?

前端 未结 4 1088
既然无缘
既然无缘 2020-12-23 10:56
class a(object):
    data={\'a\':\'aaa\',\'b\':\'bbb\',\'c\':\'ccc\'}
    def pop(self, key, *args):
            return self.data.pop(key, *args)#what is this mean.
         


        
4条回答
  •  长情又很酷
    2020-12-23 11:33

    def func(*args): 
        pass
    

    When you define a function this way, *args will be array of arguments passed to the function. This allows your function to work without knowing ahead of time how many arguments are going to be passed to it.

    You do this with keyword arguments too, using **kwargs:

    def func2(**kwargs): 
        pass
    

    See: Arbitrary argument lists


    In your case, you've defined a class which is acting like a dictionary. The dict.pop method is defined as pop(key[, default]).

    Your method doesn't use the default parameter. But, by defining your method with *args and passing *args to dict.pop(), you are allowing the caller to use the default parameter.

    In other words, you should be able to use your class's pop method like dict.pop:

    my_a = a()
    value1 = my_a.pop('key1')       # throw an exception if key1 isn't in the dict
    value2 = my_a.pop('key2', None) # return None if key2 isn't in the dict
    

提交回复
热议问题