python - 当你同时拥有 str 和 unicode 时,让类充当 Python 中的字符串

标签 python object unicode subclass

免责声明:我使用 Python 2.6 有很多奇怪的原因。就是这样。

我试图让一个对象充当具有如下属性的字符串:

class Setting(str):

    def __new__(cls, value, source):
        return super(Setting, cls).__new__(cls, value)

    def __init__(self, value, source):
        self.value = value
        self.source = source

这效果相当好。好得可怕。 ;)

但是:我需要支持 unicode 和 str 对象。所以我理想中想做的是扩展基串。不幸的是,可能出于完全合乎逻辑的原因;仅将父类(super class)更改为 basestring 不起作用并给出错误:

TypeError: The basestring type cannot be instantiated

有人知道我该如何解决这个问题吗?谢谢。 :)

最佳答案

你不能使用basestring,因为Python不允许它简单地使用,它是一个抽象的C类,只能在Python中真正用于isinstance或类似的调用。

在这种情况下,我建议使用通用方法,创建一个包含两个变量的类并覆盖任何特殊运算符以获得所需的结果(即使其表现得像 str):

class Setting:
    def __init__(self, value, source):
        self.value = value
        self.source = source

    def __add__(self, rhs):
        #keeping the object immutable
        return Setting(self.value + rhs, self.source)

然而,为了极端的Python代码,我想不出一个单一的用例(总会有更好的方法),这里有一个解决方法:

class Setting(object):

    def __new__(cls, value, source):
        #pick the correct base class
        base_class = str if isinstance(value, str) else unicode
        #construct new Setting class with correct base
        new_type = type(cls.__name__, (base_class,), dict(cls.__dict__))
        return base_class.__new__(new_type, value)

    def __init__(self, value, source):
        self.value = value
        self.source = source

这个想法只是根据给定值的类型动态创建一个具有正确基数的类。

关于python - 当你同时拥有 str 和 unicode 时,让类充当 Python 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26293550/

相关文章:

python - 如何在 python 中使用@..以及@property 和@classmethod

objective-c - 在函数中获取当前对象?

javascript - HTML Knockout 使用 Unicode 将 FontAwesome 图标添加到表格中

c# - 属性访问器

java - JDBC MySQL 连接器/J 不正确的字符串值 : '\xC3\xBCvifone...'

python - 提取列表中的 Unicode 表情符号,Python 3.x

python - 从外部脚本的 setup.py 导入变量

python - 比较和交换python中的指令

python - 趋势线图不适用于大数据集

jquery - JavaScript 新关键字和对象范围