擅长:python、mysql、java
<p>我不会从兔子洞里钻下去。即使重新分配给<code>self</code>会起作用,调试和维护也将是一场噩梦</p>
<p>我会使用classmethods来允许从一种类型创建另一种类型。分配回并不比在引擎盖下秘密更改类型更笨拙</p>
<p>classmethods是从Python中另一种类型的对象创建某种类型对象的惯用方法。对于Python不支持构造函数重载(或者任何方法重载)这一事实,它本质上是一种“变通方法”</p>
<p>显式比隐式好</p>
<pre><code>class newString(str):
@classmethod
def from_newInt(cls, new_int_obj):
return cls(str(new_int_obj))
class newInt(int):
@classmethod
def from_newString(cls, new_string_obj):
return cls(int(new_string_obj))
s = newString('1')
i = newInt(1)
print(type(newString.from_newInt(i)))
print(type(newInt.from_newString(s)))
# <class '__main__.newString'>
# <class '__main__.newInt'>
</code></pre>