You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何创建函数调用MainColors类中Colors_pencils矩阵元素

实现方案

Colors_pencils是MainColors的类属性,以下是两种常用的调用实现方式:


方案1:类内封装访问方法(推荐,便于后续统一加校验、过滤逻辑)

你可以在MainColors类中新增类方法来封装读取逻辑,无需实例化即可调用:

class MainColors(Flowers, Paints, Authors):
    Colors_pencils=(
        ['RED', 1,3],
        ['BLUE',1,4],
        ['BLACK',1,6],
        ['WHITE',1,10]
    )

    @classmethod
    def get_color_pencil(cls, color_name=None, index=None):
        # 按颜色名称查询对应配置
        if color_name:
            for item in cls.Colors_pencils:
                if item[0] == color_name.upper():
                    return item
            return None
        # 按索引位置查询对应配置
        if index is not None and 0 <= index < len(cls.Colors_pencils):
            return cls.Colors_pencils[index]
        # 不传参数默认返回全部配置
        return cls.Colors_pencils
其他函数调用示例:
def your_other_function():
    # 获取全部彩铅配置
    all_pencils = MainColors.get_color_pencil()
    # 获取红色对应的配置
    red_config = MainColors.get_color_pencil(color_name="RED")
    # 获取索引为2的配置(对应BLACK)
    black_config = MainColors.get_color_pencil(index=2)

方案2:直接访问类属性(无需额外封装,适合简单场景)

如果不需要额外的校验逻辑,直接通过类名访问类属性即可:

def your_other_function():
    # 直接读取指定位置的元素,示例读取WHITE对应的第三个参数值
    white_param = MainColors.Colors_pencils[3][2]
    # 读取全部配置
    all_pencils = MainColors.Colors_pencils

补充说明

  • 如果你已经实例化了MainColors类,也可以通过实例对象访问该属性:obj = MainColors(); print(obj.Colors_pencils)
  • 当前Colors_pencils是元组类型,内部嵌套的列表支持修改值,如果不希望内容被篡改,可以将内部的列表也替换为元组。

内容的提问来源于stack exchange,提问作者wundolab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:15:04