Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 只返回参数值的简明函数定义_Python_Python 3.x - Fatal编程技术网

Python 只返回参数值的简明函数定义

Python 只返回参数值的简明函数定义,python,python-3.x,Python,Python 3.x,我想让我的类的用户能够定义一个转换函数,该函数在类中应用多次。如果未定义此转换,则值应保持不变 这是我现在的(可能是详细的)解决方案: def do_nothing(val): return val class MyClass: def __init__(self, transformation_function = None): if transformation_function is None: self.transform = d

我想让我的类的用户能够定义一个转换函数,该函数在类中应用多次。如果未定义此转换,则值应保持不变

这是我现在的(可能是详细的)解决方案:

def do_nothing(val):
    return val

class MyClass:
    def __init__(self, transformation_function = None):
        if transformation_function is None:
            self.transform = do_nothing
        else:
            self.transform = transformation_function

我怎样才能写得更简洁?

只需使用
不做任何事
作为默认值:

def do_nothing(val):
    return val

class MyClass:
    def __init__(self, transformation_function=do_nothing):
        self.transform = transformation_function

只需使用
do\u nothing
作为默认值:

def do_nothing(val):
    return val

class MyClass:
    def __init__(self, transformation_function=do_nothing):
        self.transform = transformation_function
这个怎么样:

self.transform = transformation_function or lambda x: x
这个怎么样:

self.transform = transformation_function or lambda x: x