Python函數,它返回自己的帶有參數的簽名 (Python function which returns its own signature with parameters)


問題描述

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 BarFooAkshay SehgalorlpCamaendir)

參考文件

  1. Python function which returns its own signature with parameters (CC BY‑SA 2.5/3.0/4.0)

#Code-Generation #Python #metaprogramming #python-3.x #python-decorators






相關問題

關於編譯器中代碼生成的參考(中間表示、SSA、指令選擇、寄存器分配等)? (References on code generation in a compiler (intermediate representations, SSA, instruction selection, register allocation, etc.)?)

如何在每個新模塊中自動注入輔助類? (How to automatically inject helper classes in each new module?)

適用於Visual Studio的Python代碼生成器? (Python code generator for Visual Studio?)

為什么生成執行操作的 Java 代碼比“解釋器循環”運行得更慢? (Why does Java code generated to perform an operation run more slowly than an "interpreter loop"?)

ORM 映射的代碼生成工具 (code generation tool for ORM mapping)

Delphi 的 x86 代碼生成器框架 (x86 code generator framework for Delphi)

適用於 xpand 的 Actionscript 3 代碼美化器(MWE2 工作流程) (Actionscript 3 code beautifier for xpand (MWE2 Workflow))

Maven 中的代碼生成 (Code generation in Maven)

在自定義生成器中生成嵌套路由 (Generating nested routes in a custom generator)

是否有類似 JET(Java Emitter Templates)但沒有 Eclipse 依賴項的東西? (Is there something like JET (Java Emitter Templates) but without Eclipse-dependencies?)

Python函數,它返回自己的帶有參數的簽名 (Python function which returns its own signature with parameters)

為什麼 protobuf 更喜歡代碼生成器而不是運行時動態加載 (why protobuf prefer code-generator other than dynamic loading at runtime)







留言討論