2016-07-25 65 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.

相關問題