4
我需要一个类似字符串的类,但也需要额外的kwargs
。为此我继承str
:创建接受kwargs的str(或int或float或tuple)的子元素
class Child(str):
def __init__(self, x, **kwargs):
# some code ...
pass
inst = Child('a', y=2)
print(inst)
然而,这引起了:
Traceback (most recent call last):
File "/home/user1/Project/exp1.py", line 8, in <module>
inst = Child('a', y=2)
TypeError: 'y' is an invalid keyword argument for this function
这是相当奇怪的,因为下面的代码工作没有任何错误:
class Child(object):
def __init__(self, x, **kwargs):
# some code ...
pass
inst = Child('a', y=2)
问题:
- 为什么我得到不同的行为,试图子类时
str
,int
,float
,tuple
等相比其他类,如object
,list
,dict
等? - 如何创建一个类似字符串的类,但有 个额外的kwargs?
也许是关于'__str__'或'__unicode__'方法需要重写 –