如何让我的班级充满活力?
我想要一个带有一个附加属性的字符串,比如说是以红色还是绿色打印它。
子类化(str)不起作用,因为它是不可变的。 我看到了它的价值,但它可能很烦人。
多重继承有帮助吗? 我从来没有用过那个。
仅继承 object 并使用 self.value=str 意味着我必须自己实现所有字符串消息(如 strip)。
或者有没有办法转发它们,就像Ruby的missing_method一样?
我认为使用按实例索引的类级字典来存储颜色是可行的。 太丑了?
I want a string with one additional attribute, let's say whether to print it in red or green.
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.
Inheriting only object and using self.value=str means I have to implement all string-ness messages (like strip) myself.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
str 可以被继承,除非你使用的是非常旧的 python 版本,例如:
str can be inherited unless you are using a very old python version, for example :
通常最好使用不可变字符串和 其子类,但如果您需要一个可变的子类,这是获取它的最简单方法。
It's generally best to use immutable strings & subclasses thereof, but if you need a mutable one this is the simplest way to get it.
也许包含字符串的自定义类会是更好的方法。 您真的需要将所有字符串方法传递给底层字符串吗? 为什么不通过属性公开字符串并允许该类的使用者对其进行任何他们想要的操作?
Perhaps a custom class that contains a string would be a better approach. Do you really need to pass all string methods through to the underlying string? Why not expose the string via a property and allow consumers of the class to do whatever they wish to it?
您需要 string 的所有方法,因此扩展 string 并添加额外的详细信息。 那么如果字符串是不可变的呢? 只要让你的类也保持不变即可。 然后你无论如何都会创建新对象,这样你就不会意外地认为它是一个可变对象。
或者,如果 Python 有的话,扩展字符串的可变变体。 我对Python不够熟悉,不知道是否存在这样的结构。
You need all of string's methods, so extend string and add your extra details. So what if string is immutable? Just make your class immutable, too. Then you're creating new objects anyway so you won't accidentally mess up thinking that it's a mutable object.
Or, if Python has one, extend a mutable variant of string. I'm not familiar enough with Python to know if such a structure exists.
您可以尝试在 PyPI 中使用
stringlike
模块。 这是示例。You could try using the
stringlike
module in PyPI. Here's an example.