Is there a builtin identity function in python?

后端 未结 8 1889
情书的邮戳
情书的邮戳 2020-11-28 07:37

I\'d like to point to a function that does nothing:

def identity(*args)
    return args

my use case is something like this

         


        
8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 08:09

    The thread is pretty old. But still wanted to post this.

    It is possible to build an identity method for both arguments and objects. In the example below, ObjOut is an identity for ObjIn. All other examples above haven't dealt with dict **kwargs.

    class test(object):
        def __init__(self,*args,**kwargs):
            self.args = args
            self.kwargs = kwargs
        def identity (self):
            return self
    
    objIn=test('arg-1','arg-2','arg-3','arg-n',key1=1,key2=2,key3=3,keyn='n')
    objOut=objIn.identity()
    print('args=',objOut.args,'kwargs=',objOut.kwargs)
    
    #If you want just the arguments to be printed...
    print(test('arg-1','arg-2','arg-3','arg-n',key1=1,key2=2,key3=3,keyn='n').identity().args)
    print(test('arg-1','arg-2','arg-3','arg-n',key1=1,key2=2,key3=3,keyn='n').identity().kwargs)
    
    $ py test.py
    args= ('arg-1', 'arg-2', 'arg-3', 'arg-n') kwargs= {'key1': 1, 'keyn': 'n', 'key2': 2, 'key3': 3}
    ('arg-1', 'arg-2', 'arg-3', 'arg-n')
    {'key1': 1, 'keyn': 'n', 'key2': 2, 'key3': 3}
    

提交回复
热议问题