简体   繁体   English

为产品子图创建一个类

[英]Creating a class to product subplots

I was wondering about how to design a nice class in order to produce a matplotlib plot suitable for my purpose. 我想知道如何设计一个不错的类以生成适合我目的的matplotlib图。 The first thing that I want to obtain is a class that could be callable as follows, 我想获得的第一件事是一个可以如下调用的类,
but I have no idea of how to design such a class. 但是我不知道如何设计这样的课程。

This is how I want to use it: 这就是我要使用的方式:

fig,axs = MyClass(parameter...) 

How can I properly use this? 我该如何正确使用呢?

EDIT Thank you very much @ImportanceOfBeingErnest you give me a very good start point , my question now is since you show me how to pass the **parameter to the class, what do you think about how pass the list of variable in order to be plotted in ax1,ax2,ax3,ax4 for example ? 编辑非常感谢@ImportanceOfBeingErnest,您给了我一个很好的起点,我现在的问题是,因为您向我展示了如何将**参数传递给类,您如何考虑如何将变量列表传递给我呢?例如在ax1,ax2,ax3,ax4绘制? thanks again your help is always very precious 再次感谢您的帮助总是非常宝贵的

Essentially, you can't, or at least shouldn't. 本质上,您不能,或者至少不应该。 The return of a class should be an instance of itself. 类的返回应该是其自身的实例。

However you may call a class, eg 但是您可以打电话给一个班级,例如

import matplotlib.pyplot as plt

class MyClass():
    def __init__(self, **parameters):
        self.fig, self.axs = plt.subplots(**parameters)

    def __call__(self):
        return self.fig, self.axs

fig, axs = MyClass(figsize=(6,5))()

The drawback of this is that you directly loose any handler for the created class instance. 这样做的缺点是您直接松开了所创建类实例的任何处理程序。 This means that the above would be much simpler being written as function, 这意味着将上面的代码编写为函数要简单得多,

import matplotlib.pyplot as plt

def myfunction(**parameters):
    fig, axs = plt.subplots(**parameters)
    return fig, axs

fig, axs = myfunction(figsize=(6,5))

So in order for the use of a class to make any sense, one would probably want to store it somehow and then make use of its attributes or methods. 因此,为了使类的使用有意义,可能要以某种方式存储它,然后利用其属性或方法。

import matplotlib.pyplot as plt

class MyClass():
    def __init__(self, **parameters):
        self.fig, self.axs = plt.subplots(**parameters)

myclass = MyClass(figsize=(6,5))
fig = myclass.fig
axs = myclass.axs

Adding on to the other answer, you can also create a class that implements the __iter__ function which emulates the class as a tuple, allowing it to return fig, axs : 除了其他答案外,您还可以创建一个实现__iter__函数的类,该函数将类模拟为元组,从而允许其返回fig, axs

class MyClass:
    def __init__(self, params):
        self.fig, self.axs = plt.subplots()
        # Do stuff here
    def __iter__(self):
        for e in (self.fig, self.axs):
            yield e

fig, axs = MyClass(params)

However this is rather unorthodox, as described by @ImportanceOfBeingErnest. 但是,这非常不合常规,如@ImportanceOfBeingErnest所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM