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