【问题标题】:Class super() unable to inherit "NameError: name 'in_dir' is not defined类 super() 无法继承“NameError: name 'in_dir' is not defined
【发布时间】:2019-09-19 05:26:25
【问题描述】:

我正在尝试将输入目录路径从单独的脚本传递到主模块“qc”。

我在 qc 模块中将参数从父级传递给子级的第一次尝试如下所示:

import os

class Data:

    def __init__(self, in_dir):

        # get all inputs
        self.in_dir = in_dir # get input directory

        # get files from input directory
        self.files = os.listdir(self.in_dir) # get file list


class LAS(Data):
    """Takes in log files from parent class Data's file list"""

    def __init__(self):

        # inherit the directory from Data parent
        super().__init__(LAS, in_dir)

        # target only the .las files in the directory
        ext_las = ['.las', '.LAS', '.Las', '.LAs']
        self.lasfiles = [lasfile for lasfile in self.files if any(match in lasfile for match in ext_las)]

    def out_las(self):
        return self.lasfiles

当我从单独的脚本中调用类时,它看起来像这样:

in_dir = 'C:\\......directory path...'

Data(in_dir=in_dir)

output = LAS().out_las()

这会引发错误:

  File "C:\......", line 62, in __init__
    super().__init__(LAS, in_dir)

NameError: name 'in_dir' is not defined

我不知道如何正确调用这个父类的输入。

我做错了什么?

【问题讨论】:

  • 您的__init__ 为您的LAS 类需要接受与其父类的__init__ 方法相同的参数,否则您将如何将这些参数传递给父类?还有,你为什么要实例化Data 然后扔掉?

标签: python python-3.x class super


【解决方案1】:

很难为您指明正确的方向,但您似乎希望子类继承父类的实例 - 但事实并非如此。

以下内容可能与您的预期相近,希望对您有所帮助。

class LAS(Data):
    """Takes in log files from parent class Data's file list"""

    def __init__(self, in_dir):

        # inherit the directory from Data parent
        super().__init__(in_dir)

        # target only the .las files in the directory
        ext_las = ['.las', '.LAS', '.Las', '.LAs']
        self.lasfiles = [lasfile for lasfile in self.files if any(match in lasfile for match in ext_las)]

    def out_las(self):
        return self.lasfiles


las = LAS(in_dir='C:\\......directory path...')
output = las.out_las()

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 2013-04-09
    • 1970-01-01
    • 2020-11-07
    • 2017-01-09
    • 2017-06-14
    • 2023-03-11
    相关资源
    最近更新 更多