如何让Python类的属性支持直接调用plot()方法?
问题
我创建了如下Things类:
class Things: def __init__(self, a, b): self.a = a self.b = b def plot(self,name): px.scatter(getattr(self, name)).show()
目前可以通过以下方式对属性a或b绘图:
thing = Things([1,2,3,4], [2,2,2,2]) thing.plot('b')
但我希望能使用如下语法直接对属性绘图:
thing.b.plot()
或
thing.a.plot()
请问这种实现方式是否可行?
实现方案
完全可行,核心思路是给属性a和b包装一个带有plot方法的自定义类,替代原本的普通列表类型。
具体实现有两种可选方式:
方式1:基础包装类
先定义一个持有原始数据并实现plot方法的包装类,再在Things初始化时转换属性类型:
import plotly.express as px class PlotableData: def __init__(self, data): self.data = data def plot(self): px.scatter(self.data).show() class Things: def __init__(self, a, b): self.a = PlotableData(a) self.b = PlotableData(b)
使用时直接调用属性的plot方法即可:
thing = Things([1,2,3,4], [2,2,2,2]) thing.b.plot() thing.a.plot()
如果需要访问原始列表数据,可通过thing.a.data获取。
方式2:继承列表的增强类
让包装类直接继承list,这样属性既保留列表的所有功能,又能调用plot方法:
import plotly.express as px class PlotableList(list): def plot(self): px.scatter(self).show() class Things: def __init__(self, a, b): self.a = PlotableList(a) self.b = PlotableList(b)
这种方式下,除了plot方法,列表的常规操作也能正常使用:
thing = Things([1,2,3,4], [2,2,2,2]) thing.a.plot() print(thing.b[0]) # 输出2,保留列表索引访问功能
内容的提问来源于stack exchange,提问作者Mirk
相关产品推荐
相关产品推荐

