本文介绍了如何替换函数的__str__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将python函数的字符串表示改为函数名称。



例如,对于某些函数

  def blah(x):
...

str(blah)目前给出

 < ; function blah at 0x10127b578> 

因此,我将 __ str __ 替换为:

  blah .__ str __ = lambda:'blah'

但它不会被 str(blah)

所调用。

是否可以为函数更改 __ str __

正如Joran所说:

$ p $ class NamedFunction:
def __init __(self,name,f):
self .f = f
self.name = name

def __call __(self,* args,** kwargs):
返回self.f(* args,** kwargs)

def __str __(self):
return self.name


f = NamedFunction(lambda:'blah',lambda:'blah' )
print(f())
print(f)


I want to change the string representation of a python function to be just the function name.

Eg for some function

def blah(x):
 ...

str(blah) currently gives

<function blah at 0x10127b578>

So I replace __str__ like this:

blah.__str__=lambda: 'blah'

but it doesn't get called by str(blah).

Is it possible to change __str__ for a function?

解决方案

As Joran said:

class NamedFunction:
    def __init__(self, name, f):
        self.f = f
        self.name = name

    def __call__(self, *args, **kwargs):
        return self.f(*args, **kwargs)

    def __str__(self):
        return self.name


f = NamedFunction("lambda: 'blah'", lambda: 'blah')
print(f())
print(f)

这篇关于如何替换函数的__str__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 04:43