問題描述
Python函數,它返回自己的帶有參數的簽名 (Python function which returns its own signature with parameters)
標記為已解決,因為:已解決的解決方案為問題提供了足夠好的解決方案,儘管它並不能完全解決按需動態生成函數名稱的問題。
我想要生成一個函數,該函數返回其自己的帶有參數的簽名。這在 Python 中可能嗎?因此,該函數由調用本身生成,並返回代表其自身名稱和參數的字符串。
這是我正在尋找的一個簡單示例:
class Object(object):
#Impl here?
pass
a = Object()
returned_string = a.foo(param1 = 1, param2 = "cheese")
print(returned_string)
#should print: a.foo(param1 = 1, param2 = "cheese")
#or print: foo(param1 = 1, param2 = "cheese")
重要的是,foo 是一個任意名稱,不應該是“硬編碼”的。但已生成。
代碼應允許以下內容:
print(a.doodle(param1 = 32)) #prints: doodle(param1 = 32)
print(a.bar(param42 = "pi")) #prints: bar(param42 = "pi")
無需定義更多功能。
謝謝:)
參考解法
方法 1:
I am assuming what you mean is that once you have created an object, the function is able to return its own input parameters for that object. You can of course modify it to look like a string but what you want to return is the input parameters that are the signature of that object and funciton foo
class Object():
def foo(self, param1, param2):
self.param1 = param1
self.param2 = param2
return self.__dict__
a = Object()
returned_string = a.foo(param1 = 1, param2 = "cheese")
print(returned_string)
{'param1': 1, 'param2': 'cheese'}
Returning it as a string ‑
import inspect
class Object():
def foo(self, param1, param2):
self.param1 = param1
self.param2 = param2
d = self.__dict__
f = inspect.stack()[0][3]
return f+'('+', '.join([' = '.join([str(j) for j in i]) for i in d.items()])+')'
a = Object()
returned_string = a.foo(param1 = 1, param2 = "cheese")
print(returned_string)
foo(param1 = 1, param2 = cheese)
方法 2:
You should be able to do what you want using **kwargs
. As an example:
def my_args_are(**kwargs):
return "my_args_are({})".format(
", ".join("{0} = {1!r}".format(arg, val)
for arg, val in kwargs.items()))
It works:
>>> my_args_are(param1 = 1, param2 = "cheese")
"my_args_are(param1 = 1, param2 = 'cheese')"
If you don't want to hardcode the name you can use inspect
:
import inspect
def my_args_are(**kwargs):
fname = inspect.currentframe().f_code.co_name
argstr = ", ".join("{0} = {1!r}".format(arg, val)
for arg, val in kwargs.items()))
return "{}({})".format(fname, argstr)
方法 3:
So here's the function you want:
import inspect
class Object(object):
def your_function(**options):
return f"{inspect.stack()[0][3]}({', '.join([str(key) + ' = ' + str(options[key]) for key in options.keys()])})"
</code></pre>
So if you do:
a = Object()
and
a.your_function(abc="abc", ert=3)
it will return:
your_function(abc = abc, ert = 3)
(by BarFoo、Akshay Sehgal、orlp、Camaendir)
參考文件