子类int和重写__init__方法 - Python的
问题描述:
Possible Duplicate:
inheritance from str or int子类int和重写__init__方法 - Python的
乡亲嗨,
我想继承int类没有任何成功。这里是我的尝试:
class SpecialInt(int):
def __init__(self, x, base=10, important_text=''):
int.__init__(self, x, base)
self.important_text=important_text
如果我执行以下操作:
integer = SpecialInt(123, 10, 'rage of the unicorns')
我得到这个错误:
TypeRror: int() takes at most 2 arguments (3 given)
任何想法? :)
答
见__new__
:
__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.
http://stackoverflow.com/questions/3238350/subclassing-int-in-python – 2011-04-17 14:09:55
重复。看到这里:http://stackoverflow.com/questions/2673651/inheritance-from-str-or-int – 2011-04-17 14:06:01