2016-07-25 36 views
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) 

问题:

  • 为什么我得到不同的行为,试图子类时strintfloattuple等相比其他类,如objectlistdict等?
  • 如何创建一个类似字符串的类,但有 个额外的kwargs?
+0

也许是关于'__str__'或'__unicode__'方法需要重写 –

回答

7

您需要在这种情况下,以覆盖__new__,不__init__

>>> class Child(str): 
... def __new__(cls, s, **kwargs): 
...  inst = str.__new__(cls, s) 
...  inst.__dict__.update(kwargs) 
...  return inst 
... 
>>> c = Child("foo") 
>>> c.upper() 
'FOO' 
>>> c = Child("foo", y="banana") 
>>> c.upper() 
'FOO' 
>>> c.y 
'banana' 
>>> 

的答案见here为什么继承一成不变的类型,如strintfloat当重写__init__不工作:

__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

相关问题