python - 在另一个函数中用作参数时,如何将自定义 Python 对象表示为字符串?

标签 python class object matplotlib repr

我正在尝试制作一个名为Color的简单对象。我希望它具有与编码为十六进制颜色的字符串相同的功能。它看起来可以工作,但不具有相同的功能。

编辑:回应下面已接受的答案:

import pandas as pd
from matplotlib.colors import to_rgb, rgb2hex


class Color(str):
    def __new__(cls, value, *args, **kwargs):
        # explicitly only pass value to the str constructor
        cls.color = rgb2hex(to_rgb(value))
        return super(Color, cls).__new__(cls, cls.color)

x = pd.Series([Color("fuchsia"), Color("black")])
print(x)
# 0    #ff00ff
# 1    #000000
# dtype: object
print("Should be fuchsia but it's black", x[0].color)
# Should be fuchsia but it's black #000000
print("Should be black", x[0].color)
# Should be black #000000

原文:

例如,以下操作有效:

print(color)
print(pd.Series(color))
print(to_rgb(str(color)))

但这并不:

print(to_rgb(color))

我不明白为什么这不起作用。我已经尝试过,但它不适合这种情况:Python, represent non-string object as string?

from matplotlib.colors import hex2color, to_rgb, to_rgba


class Color(object):
    # Built in
    def __init__(self, color):
        self.color = rgb2hex(to_rgb(color))
    def __repr__(self):
        return self.color
    def __str__(self):
        return self.color

color = Color("black")
print(color)
# #000000
print(pd.Series(color))
# 0    #000000
# dtype: object
print(to_rgb(str(color)))
# (0.0, 0.0, 0.0)
print(to_rgb(color))

这是错误:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~/anaconda/envs/µ_env/lib/python3.6/site-packages/matplotlib/colors.py in to_rgba(c, alpha)
    173     try:
--> 174         rgba = _colors_full_map.cache[c, alpha]
    175     except (KeyError, TypeError):  # Not in cache, or unhashable.

KeyError: (#000000, None)

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-35-a478f942e1d2> in <module>
     16 print(pd.Series(color))
     17 print(to_rgb(str(color)))
---> 18 print(to_rgb(color))

~/anaconda/envs/µ_env/lib/python3.6/site-packages/matplotlib/colors.py in to_rgb(c)
    279 def to_rgb(c):
    280     """Convert *c* to an RGB color, silently dropping the alpha channel."""
--> 281     return to_rgba(c)[:3]
    282 
    283 

~/anaconda/envs/µ_env/lib/python3.6/site-packages/matplotlib/colors.py in to_rgba(c, alpha)
    174         rgba = _colors_full_map.cache[c, alpha]
    175     except (KeyError, TypeError):  # Not in cache, or unhashable.
--> 176         rgba = _to_rgba_no_colorcycle(c, alpha)
    177         try:
    178             _colors_full_map.cache[c, alpha] = rgba

~/anaconda/envs/µ_env/lib/python3.6/site-packages/matplotlib/colors.py in _to_rgba_no_colorcycle(c, alpha)
    225         # float)` and `np.array(...).astype(float)` all convert "0.5" to 0.5.
    226         # Test dimensionality to reject single floats.
--> 227         raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
    228     # Return a tuple to prevent the cached value from being modified.
    229     c = tuple(c.astype(float))

ValueError: Invalid RGBA argument: #000000

最佳答案

也许您想要子类化 str 来提供您的字符串。

import pandas as pd
from matplotlib.colors import to_rgb, rgb2hex


class Color(str):
    def __new__(cls, value, *args, **kwargs):
        # explicitly only pass value to the str constructor
        v = rgb2hex(to_rgb(value))
        return super(Color, cls).__new__(cls, v)


color = Color("fuchsia")

print(color)
print(pd.Series(color))
print(to_rgb(str(color)))
print(to_rgb(color))

输出

#ff00ff
0    #ff00ff
dtype: object
(1.0, 0.0, 1.0)
(1.0, 0.0, 1.0)

如果你想将初始值存储在字符串中,你可以这样做

class Color(str):
    def __new__(cls, value, *args, **kwargs):
        # explicitly only pass value to the str constructor
        v = rgb2hex(to_rgb(value))
        return super(Color, cls).__new__(cls, v)

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

关于python - 在另一个函数中用作参数时,如何将自定义 Python 对象表示为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56979723/

相关文章:

c# - 从 .Net 应用程序打开 Python 脚本命令窗口时,如何保持打开状态?

c++ - 智能指针的类,它指向哪里?

python - 如何通过方法使用 numba.jit

javascript - 循环包含其他对象数组的对象数组。并进行一定的计算

python - PyCharm 类型暗示​​怪异

python - 有没有办法将两个列表与 xarray 数据变量中的相应信息连接起来?

python - 将包添加到 pylint 异常

c++ - 从具有静态结构的基类派生

javascript - 如何在不是对象或函数的对象实例上进行原型(prototype)设计?

python - 如何在 python 中使用 pickle 保存带有列表的对象?