Python 继承中装饰器的作用域问题

Python 继承中装饰器的作用域问题,python,inheritance,decorator,Python,Inheritance,Decorator,我试图检查一个类是否能够通过装饰器拥有一个文件,使用下面的代码,我发现即使子类CSVStorageHandler调用其父类的checkIfNoStorageHandler变量func也超出了范围 这相当令人困惑,有人能帮忙吗 class StorageHandler(object): def __init__(self): self.output_file = self.openFile() def checkIfNoStorageHandler(func):

我试图检查一个类是否能够通过装饰器拥有一个文件,使用下面的代码,我发现即使子类
CSVStorageHandler
调用其父类的
checkIfNoStorageHandler
变量
func
也超出了范围

这相当令人困惑,有人能帮忙吗

class StorageHandler(object):
    def __init__(self):
        self.output_file = self.openFile()

    def checkIfNoStorageHandler(func):
        def createFileByStorageHandler(self, *args, **kwargs):
            print func
            if self.__class__.__name__ == "CSVStorageHandler":
                return self.func()
            else:
                print ("class " + self.__class__.__name__ + " don't store file by default")
                return None
        return createFileByStorageHandler

    @checkIfNoStorageHandler    
    def openFile(self):
        return open('./log.txt', 'w')

class CSVStorageHandler(StorageHandler):
    def doNothing(self):
        pass
class NoStorageHandler(StorageHandler):
    def doNothing(self):
        pass


test = CSVStorageHandler()
错误消息

Traceback (most recent call last):
  File "tset_decorator_inheritance.py", line 27, in <module>
    test = CSVStorageHandler()
  File "tset_decorator_inheritance.py", line 3, in __init__
    self.output_file = self.openFile()
  File "tset_decorator_inheritance.py", line 9, in createFileByStorageHandler
    return self.func()
AttributeError: 'CSVStorageHandler' object has no attribute 'func'
回溯(最近一次呼叫最后一次):
文件“tset_decorator_heritation.py”,第27行,在
test=CSVStorageHandler()
文件“tset_decorator_heritation.py”,第3行,在uu init中__
self.output_file=self.openFile()
createFileByStorageHandler中的第9行文件“tset_decorator_inheritation.py”
返回self.func()
AttributeError:'CSVStorageHandler'对象没有属性'func'

func
在范围内,但您的代码正在尝试访问
self.func
。也许您想在第9行使用
func()
而不是
self.func()

self.func()
是一次大胆的尝试,但没有用,因为点语法永远不会关心名为
func
的本地

您希望确保函数接收到
self
,因此只需将其传入即可

return func(self, *args, **kwargs)

我看不到您将
func
属性分配给
StorageHandler
或其任何子级的任何地方。所以这个错误消息完全有意义。这与范围界定无关。你只是想做
return func()
而不是
return self.func()
?谢谢你的建议,但是
func()
openFile(self)
,我需要
self.func()
让它调用下面正确的see@Eevee的答案。谢谢你的回答,它奏效了,但是
self.func()之间有什么区别
vs
func(self)
,是不是完全一样,你们都只是把
self
传递给函数?不是
self.func()
self
上查找
func
作为方法
func(self)
self
传递给名为
func
的本地或全局函数
self.func()
最终会传递
self
,是的,但它首先要做的是找到函数。