栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何实现函数的__str__?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何实现函数的__str__?

Python中的函数只是一个可调用对象。使用

def
定义函数是创建此类对象的 一种
方法。但是实际上并没有阻止您创建可调用类型并创建其实例以获取函数的方法。

因此,以下两项基本相同:

def foo ():    print('hello world')class FooFunction:    def __call__ (self):        print('hello world')foo = FooFunction()

除了最后一个显然允许我们设置函数类型的特殊方法(如

__str__
和)
__repr__

class FooFunction:    def __call__ (self):        print('hello world')    def __str__ (self):        return 'Foo function'foo = FooFunction()print(foo) # Foo function

但是为此创建类型变得有些乏味,并且也使理解函数的功能变得更加困难:毕竟,

def
语法允许我们 定义函数主体。因此,我们希望保持这种状态!

幸运的是,Python具有称为装饰器的强大功能,我们可以在这里使用它。我们可以创建一个函数装饰器,将任何函数包装在自定义类型内,该自定义类型将调用的自定义函数

__str__
。可能看起来像这样:

def with_str (str_func):    def wrapper (f):        class FuncType: def __call__ (self, *args, **kwargs):     # call the original function     return f(*args, **kwargs) def __str__ (self):     # call the custom __str__ function     return str_func()        # decorate with functool.wraps to make the resulting function appear like f        return functools.wraps(f)(FuncType())    return wrapper

然后,我们可以

__str__
通过简单地装饰它来将其添加到任何函数。看起来像这样:

def foo_str ():    return 'This is the __str__ for the foo function'@with_str(foo_str)def foo ():    print('hello world')>>> str(foo)'This is the __str__ for the foo function'>>> foo()hello world

显然,这样做有一些局限性和缺点,因为您无法 准确地 重现

def
该装饰器中新功能的作用。

例如,使用

inspect
模块查看参数将无法正常工作:对于可调用类型,它将包含
self
参数,而在使用通用修饰符时,它将只能报告的详细信息
wrapper
。但是,可能会有
一些 解决方案,例如在本问题中讨论的解决方案, 这些 解决方案将使您能够还原 某些 功能。

但这通常意味着您要花费很多精力才能使

__str__
功能对象上的工作变得很少使用。因此,您应该考虑
__str__
您的功能是否确实需要实现,以及您将对这些功能执行哪种操作。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/662627.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号