【问题标题】:How can I use attributes from the class above?如何使用上述类的属性?
【发布时间】: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 并删除了不需要的部分代码。现在怎么更清楚了

标签: python class arguments


【解决方案1】:

更仔细地查看代码并猜测“self.arguments”是指“self”的“attributes”:您似乎处于给人的印象是内部类以某种方式与外部类相关联,因此内部类的实例隐式地具有与它们一起创建的外部类的一些实例。在 Python 中,情况并非如此。 self.base_path 无法解析某些Folders 实例的base_path 属性,因为self 不是Folders 实例;它是一个Save 实例,而Save 不是Folders 的子类。它只是Folders 中定义,这只是命名空间(即,外部代码需要将类称为Folders.Save 而不仅仅是Save)。

您应该完全重新设计它。 None of this makes sense design-wise in the first place:说你有“一个文件夹”或“一个保存”是什么意思?这些东西是什么?请记住,“object”是 thing 的一个花哨词,而“class”是“kind of thing”的一个花哨词。

无论如何,向类实例提供信息的自然方式是将其传递给构造函数,然后让__init__ 将该信息存储在某处。您知道,就像您一开始创建 Folders 实例时已经在做的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 2012-10-01
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多