如何在课堂上赋予弦乐性?

Tob*_*ias 6 python string multiple-inheritance immutability

我想要一个带有一个附加属性的字符串,让我们说是用红色还是绿色打印它.

子类化(str)不起作用,因为它是不可变的.我看到了价值,但它可能很烦人.

多重遗产有帮助吗?我从来没用过那个.

仅继承对象并使用self.value = str意味着我必须自己实现所有字符串消息(如strip).

或者有没有办法转发它们,比如Ruby的missing_method?

我认为使用实例索引的类级别字典来存储颜色可能会起作用.太丑了?

Lup*_*uch 6

除非您使用的是非常旧的python版本,否则str可以继承,例如:

>>> class A(str):
...    def __new__(cls, color, *args, **kwargs):
...        newobj = str.__new__(cls, *args, **kwargs)
...        newobj.color = color
...        return newobj
>>> a = A("#fff", "horse")
>>> a.color
'#fff'
>>> a
'horse'
>>> a.startswith("h")
True
Run Code Online (Sandbox Code Playgroud)

  • 这很好.但是你需要小心这种方法.如果您进行了任何字符串操作(title(),+,...),则结果将为str而不是A. (3认同)