我创建了这个类

class Things:
    def __init__(self, a, b):
        self.a = a
        self.b = b
    
    def plot(self,name):
        px.scatter(getattr(self, name)).show()

在本例中,可以将属性ab绘制为

thing = Things([1,2,3,4], [2,2,2,2])
thing.plot('b')

但我希望能够使用以下语法绘制属性:

thing.b.plot()  

thing.a.plot()

你知道这是否可能吗?

推荐答案

是的,这是可能的.为此,您可以使用另一个支持类来完成此任务.

import matplotlib.pyplot as plt

class PlotAttribute:
    def __init__(self, data):
        self.data = data

    def plot(self):
        plt.scatter(range(len(self.data)), self.data)
        plt.show()

class Things:
    def __init__(self, a, b):
        self.a = PlotAttribute(a)
        self.b = PlotAttribute(b)

现在你可以这样做了

thing = Things([1, 2, 3, 4], [2, 2, 2, 2])
thing.b.plot()  # Plots the 'b' attribute 
thing.a.plot()  # Plots the 'a' attribute 

Python相关问答推荐

将列中的滚动值集转换为单元格中的单个值

Pandas基于另一列的价值的新列

两极:滚动组,起始指数由不同列设置

使用pandas MultiIndex进行不连续 Select

取相框中一列的第二位数字

CustomTKinter-向表单添加额外的输入字段

如果我已经使用了time,如何要求Python在12秒后执行另一个操作.sleep

绘制系列时如何反转轴?

从管道将Python应用程序部署到Azure Web应用程序,不包括需求包

返回nxon矩阵的diag元素,而不使用for循环

'discord.ext. commanders.cog没有属性监听器'

删除最后一个pip安装的包

海运图:调整行和列标签

大小为M的第N位_计数(或人口计数)的公式

通过pandas向每个非空单元格添加子字符串

关于Python异步编程的问题和使用await/await def关键字

在含噪声的3D点网格中识别4连通点模式

python中字符串的条件替换

如果满足某些条件,则用另一个数据帧列中的值填充空数据帧或数组

未知依赖项pin—1阻止conda安装""