如何在课堂上给予丝丝细腻? [英] How to bestow string-ness on my class?

查看:86
本文介绍了如何在课堂上给予丝丝细腻?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want a string with one additional attribute, let's say whether to print it in red or green.

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

Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.

多重继承可以帮助吗?我从没用过.

Can multiple inheritence help? I never used that.

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

Inheriting only object and using self.value=str means I have to implement all string-ness messages (like strip) myself.

或者像Ruby的missing_method一样,有什么方法可以转发它们?

Or is there a way to forward them, like Ruby's missing_method?

我认为使用按实例索引的类级字典来存储颜色是可行的.太丑了吗?

I think using a class-level dictionary indexed by instance to store the color could work. Too ugly?

推荐答案

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

str can be inherited unless you are using a very old python version, for example :

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

这篇关于如何在课堂上给予丝丝细腻?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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