zez*_*llo 2 python string signature kwargs python-3.x
我希望能够改变输出__str__(),并希望为此添加**kwargs.
问题:似乎无法更改函数的签名.
例如:
#!/usr/bin/env python3
class my_printable_obj(object):
def __init__(self, s):
self.content = s
def __str__(self, **kwargs):
fancy = kwargs.get('fancy', '')
return str(self.content) + fancy
M = my_printable_obj("Something to print")
print(str(M))
print(str(M, fancy=' + a fancy part'))
Run Code Online (Sandbox Code Playgroud)
输出:
$ ./test_script3str.py
Something to print
Traceback (most recent call last):
File "./test_script3str.py", line 17, in <module>
print(str(M, fancy=' + a fancy part'))
TypeError: 'fancy' is an invalid keyword argument for this function
Run Code Online (Sandbox Code Playgroud)
我注意到,尽管有TypeError消息,python确实使用了my_printable_obj.__str__()(print('here')在开始时添加一个__str__()让我们很容易观察到这一点).
有没有解决办法,或者由于某种原因不可能?我应该更好地定义另一个函数,比如into_str(self, **kwargs)和使用M.into_str(fancy=' something more')而不是__str__()?
注意:写这个:
def __str__(self, fancy=''):
return str(self.content) + fancy
Run Code Online (Sandbox Code Playgroud)
给出完全相同的错误.
你用kwarg调用的函数是str(内置函数).
str()会__str__在您的对象上调用该方法.
也许你在寻找的是 __format__
>>> class MyPrintableObj(object):
def __init__(self, s):
self.content = s
def __format__(self, formatstr):
return str(self.content) + formatstr
>>> m = MyPrintableObj("Something to print")
>>> '{: a fancy string}'.format(m)
'Something to print a fancy string'
Run Code Online (Sandbox Code Playgroud)