从str或int继承

发布于 2021-01-29 16:18:14

为什么我在创建从str(或从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__?为什么?

关注者
0
被浏览
44
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。
    >>> 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__是一个类方法,因此我已经调用了第一个参数cls

    看到这里了解更多信息

    >>> 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'
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看