如何从函数定义中设置函数 properties/attributes?
How to set function properties/attributes from within the function definition?
如何在函数定义中设置函数 properties/attributes?
例如,有没有办法从函数定义中实现这一点:
def test():
pass
test.order = 1
所以类似于:
def test():
self.order = 1
pass
print(test.order)
在python中,函数也是对象,当然可以设置函数的属性。
但是函数的属性与函数的逻辑无关,因此您可能希望在函数外定义它们。 decorator
可能是个不错的选择。
def function_mark(**kwargs):
def decoractor(func):
func._my_info = kwargs
return func
return decoractor
@function_mark(order=1)
def test():
pass
print(test._my_info)
如何在函数定义中设置函数 properties/attributes?
例如,有没有办法从函数定义中实现这一点:
def test():
pass
test.order = 1
所以类似于:
def test():
self.order = 1
pass
print(test.order)
在python中,函数也是对象,当然可以设置函数的属性。
但是函数的属性与函数的逻辑无关,因此您可能希望在函数外定义它们。 decorator
可能是个不错的选择。
def function_mark(**kwargs):
def decoractor(func):
func._my_info = kwargs
return func
return decoractor
@function_mark(order=1)
def test():
pass
print(test._my_info)