繁体   English   中英

NoneType 对象在类定义的装饰器上不可调用

[英]NoneType object is not callable on class defined decorator

我有一个奇怪的特定问题,与 SE 上经常发现的总体NoneType对象问题有关。 我正在尝试使用装饰器函数打开文件,而装饰器函数应用特定于文件类型的特定操作(又名文本、富文本、PDF 等)

该过程解析良好,并通过对象创建和类初始化工作,但是当我尝试调用PDFReader函数时抛出异常,该函数当前只有"Reached"的调试打印语句。

我发现这是由于我使用的双重定义方法,因为函数调用似乎在父函数中,我试图访问的实际参数只能在子函数中使用。

我的问题是:如果我希望有一个通过self使用对象初始化变量的类绑定装饰器,我该如何修复我的代码或者有更好的方法来实现我正在尝试的东西?

文件处理程序.py:

class Fileloader(object):

    class _decorators():
        @classmethod
        def _reader(cls, decorated):
            print('File opened in Read-Only Mode')
             #---No error if "decorated()" called here.

            def decorator(self, *args, **kwargs):
                print(self._file) #---Prints to console then throws the exception
                decorated(self, *args, **kwargs)
                ...


    def __init__(self, filename, mode='rb'):
        self._file = filename
        self._mode = mode
        print(self._file)

    @_decorators._reader
    def pdfReader(self):
        print("reached") #---never reached
        ...


Test = Fileloader('test.pdf')
Test.pdfReader()

超级简单的修复,我只是盯着代码看了很久才看到它。

感谢@martineau 指出我的外部装饰器没有返回任何东西。

固定代码是这样

class Fileloader(object):
    class _decorators():
        @classmethod
        def _reader(cls, decorated):
            print('File opened in Read-Only Mode')

            def decorator(self, *args, **kwargs):
                print(self._file)
                with open(self._file, mode=self._mode) as self.f:
                    print('Decorator')
                    decorated(self, *args, **kwargs)
                    pass

            return decorator #<----- Added this and it works as it should

编辑:对于在我之后需要解释发生的事情的任何人,我创建了一个内部类class _decorators()以允许使用嵌套函数( @classmethod def_reader(cls, decorated) ,它采用cls所需的参数( class 的缩写)和decorated (这是我用于传递的函数的关键字)。然后定义了一个内部函数,以便我可以访问该对象的self字典,这是由于 Python 的工作方式而完成的。

Python 将首先解析代码的一部分,所以如果我只有内部函数decorator那么它会传递一个异常,因为此时没有self属性。

在它通过Test = Fileloader('test.pdf')初始化对象之后,它确实有一个self属性,可以在运行时由内部函数decorator访问。 因此,需要嵌套函数,因为解析器将在解析时间期间通过内部函数,但在对象被实例化时会在运行时返回并读取它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM