How to share an instance created in main with a class in another module

74 views Asked by At

I am having a problem with how to share a class instance between modules. Below is not the actual code, it is a simplified representation of what I'm trying to do. The variable in question is thePlot. If I make it a global, I get 'global name not defined' type errors. If I don't use a global, then the 'draw' method in the shapes modules can't find it.

I get errors when the draw() method is called and it tries to execute the 'thePlot' method 'plot'.

* Main module *****************
import matplotlib as plt
import plotter
import shapes

main():
    thePlot = plotter.plotter()
    cyl = shapes.cylinder(r, c, n, color)
    cyl.draw()
    plt.show()

* shapes module *******************
import main
import plotter

class shapes(self):
    def __init__(self):
        pass
    def cylinder(r, c, n, color):
    self.r = r
    self.c = c
    self.n = n
    self.color = color

def draw(self):
    self.x = calculate list of x coordinates
    self.y = calculate list of y coordinates
    self.z = calculate list of z coordinates
    global thePlot
    * This line causes the error
    thePlot.plot(self.x, self.y, self.z, self.color)

* plotter module ******************
import matplotlib as plt

class plotter(self):
    def __init__(self):
        self.fig = plt.figure()
        self.ax = fig.add_subplot(111, projection='3d')

    def plot(self, x, y, z, color):
        self.ax.plot_wireframe(x, y, z, color)
2

There are 2 answers

3
warvariuc On BEST ANSWER
* Main module *****************
import matplotlib as plt
import plotter
import shapes

def main():
    global thePlot
    thePlot = plotter.plotter()
    cyl = shapes.cylinder(r, c, n, color)
    cyl.draw()
    plt.show()

And this:

global thePlot
* This line causes the error
thePlot.plot(self.x, self.y, self.z, self.color)

Should become:

main.thePlot.plot(self.x, self.y, self.z, self.color)

With the condition that main.main() was called before.

1
cameron-f On

I'm not familiar with matplotlib, but it looks like there is a similar question Add cylinder to plot . How about this adapted code?

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

"""
def cyl():
    x = None
    y = None
    z = None
    return
"""
def cyl():
    x=np.linspace(-1, 1, 100)
    z=np.linspace(-2, 2, 100)
    Xc, Zc=np.meshgrid(x, z)
    Yc = np.sqrt(1-Xc**2)
    return Xc, Yc, Zc

Xc, Yc, Zc = cyl()

#draw parameters                                                                                                                                                          
rstride = 20
cstride = 10
ax.plot_surface(Xc, Yc, Zc, alpha=0.2, rstride=rstride, cstride=cstride)
ax.plot_surface(Xc, -Yc, Zc, alpha=0.2, rstride=rstride, cstride=cstride)

ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
plt.show()