从str或int继承 [英] inheritance from str or int

查看:166
本文介绍了从str或int继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我在创建一个继承自str(或者也来自int)的类时遇到问题

Why I have problem creating a class inheriting from str (or also from int)

class C(str):
   def __init__(self, a, b):
     str.__init__(self,a)
     self.b = b

C("a", "B")

TypeError: str() takes at most 1 argument (2 given)



如果我尝试使用 int 而不是 str ,也会发生相同的情况,但它适用于自定义类。我需要使用 __ new __ 而不是 __ init __ ?为什么?

tha same happens if I try to use int instead of str, but it works with custom classes. I need to use __new__ instead of __init__? why?

推荐答案

>>> class C(str):
...     def __new__(cls, *args, **kw):
...         return str.__new__(cls, *args, **kw)
... 
>>> c = C("hello world")
>>> type(c)
<class '__main__.C'>

>>> c.__class__.__mro__
(<class '__main__.C'>, <type 'str'>, <type 'basestring'>, <type 'object'>)

由于 __ init __ 在构造对象后被调用,修改不可变类型的值为时已晚。请注意 __ new __ 是一个classmethod,所以我调用了第一个参数 cls

Since __init__ is called after the object is constructed, it is too late to modify the value for immutable types. Note that __new__ is a classmethod, so I have called the first parameter cls

有关详细信息,请参见此处

See here for more information

>>> class C(str):
...     def __new__(cls, value, meta):
...         obj = str.__new__(cls, value)
...         obj.meta = meta
...         return obj
... 
>>> c = C("hello world", "meta")
>>> c
'hello world'
>>> c.meta
'meta'

这篇关于从str或int继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆