AttributeError:“非类型”对象没有属性“接收器”

2024-06-10 18:47:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要开发一个演示ETL系统,该系统需要从以下流畅的python格式运行

ETL().source(source_args).sink(sink_args).run()

我做了class ETL()之后我在类中做了一个函数source和函数sink。 代码如下所示:

class ETL:

    def source(self, data_source: str):
        if data_source == 'Simulation':
            simulation()
        elif data_source == 'File':
            main()

    def sink(self, data_sink: str):
        if data_sink == 'Console':
            command = 'Continue'
            user_command = input('Please type to Continue or to Stop!')
            while command != 'Stop':
                simulation()

        else:
            pass

ETL().source('Simulation').sink('Console')

运行文件时,我收到以下错误:

AttributeError: 'NoneType' object has no attribute 'sink'

我错在哪里?如何添加最后一个方法.run()? 我从另一个文件中获取simulation()函数,但这不是问题所在


Tags: 函数runselfsourcedataif系统def
3条回答

NoneType意味着您实际上并没有得到一个ETL实例,而不是想要调用的ETL实例。这是因为函数调用失败或返回意外结果

一种改变的方法是在函数中添加一个返回

标准run()方法调用作为目标参数传递给对象构造函数的可调用对象,其顺序参数和关键字参数分别取自args和kwargs参数。每次创建对象时,都会调用一个方法。该方法被命名为构造函数

构造函数是使用函数init创建的。作为参数,我们编写self关键字,它引用自身(对象)。函数init(self)构建对象。这里不仅可以设置变量,还可以调用类方法。初始化对象所需的一切。它可能看起来像这样:

def __init__(self):
       self.source()
       self.sink()

您已经找到了答案,但我将向您的代码中添加一些return self

class ETL:

    def source(self, data_source: str):
        if data_source == 'Simulation':
            simulation()
        elif data_source == 'File':
            main()
        return self

    def sink(self, data_sink: str):
        if data_sink == 'Console':
            command = 'Continue'
            user_command = input('Please type to Continue or to Stop!')
            while command != 'Stop':
                simulation()
        return self

ETL().source('Simulation').sink('Console')

上面的代码现在可以正常工作,没有错误

但是,您还询问了run()方法。我想知道那该怎么办。对我来说,它看起来像是sink()方法,有一个while循环正在做运行的事情

也许你本想这么做:

# code elided ...
    def sink(self, data_sink: str):
        self.data_sink = data_sink
        return self

    def run(self):
        if self.data_sink == 'Console':
            command = 'Continue'
            user_command = input('Please type to Continue or to Stop!')
            while command != 'Stop':
                simulation()

# Now this will work:
ETL().source(source_args).sink(sink_args).run()

我认为这里的问题是您的方法source()没有返回任何内容,因此您将None作为输出。然后,当应用第二个方法(sink())时,您不再使用ETL的实例,而是使用ETL().source('Simulation')的输出。您应该尝试以下方法:

foo = ETL()
foo.source('Simulation')
foo.sink('Console')

另一种解决方案(尽管我认为这不是最好的方法)是在source方法中返回self。这将允许您继续使用类的实例,并运行所需的代码行

相关问题 更多 >