【发布时间】:2021-12-12 18:07:00
【问题描述】:
我创建了一个具有创建文件夹路径功能的外部类,用户决定路径和内部类将绘图图像保存到该文件夹,用户决定文件名和格式。我的问题是我不能使用外部类属性。 如何使用上述类的属性?这种依赖还有另一种干净的方式吗?
import os
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
import pandas as pd
# Outter class
class Folders():
def __init__(self,
base_path="folder_name1/folder_name2"):
self.base_path = base_path
pass
# Function to create path of folders
def create(self):
try:
os.makedirs(self.base_path)
except FileExistsError:
# directory already exists
pass
# Inner class
class Save:
def __init__(self,current_date = datetime.today().strftime('%Y_%m_%d@%H_%M_%S'),
image_format = '.png',
image_name = '/name_of_image'):
self.current_date = current_date
self.image_name = image_name
# Function to save the images in the created path
def image1(self):
f.savefig(self.base_path+self.image_name+self.image_format, bbox_inches='tight')
# Plotting the figure
x = np.linspace(0, 6*np.pi, 100)
y = np.sin(x)
f = plt.figure()
ax = f.add_subplot(111)
ax.plot(x, y, 'r-')
# Creates path of folders
folder = Folders()
folder.create()
# Save images with default arguments
save = folder.Save()
save.image1()
# Save images with chosen arguments
savea = folder.Save(image_format='.jpg', image_name='image_name')
savea.image1()
【问题讨论】:
-
我在您显示的代码中的任何地方都没有看到任何名为
arguments的东西,所以当您说“外部类”或“上面的类”时,我不知道您在说什么"。 -
我已经编辑了程序,添加了一些 cmets 并删除了不需要的部分代码。现在怎么更清楚了