当我使用super()从另一个类进行扩展时,发生了一个奇怪的属性

时间:2019-06-13 05:53:47

标签: python

当我使用super()从另一个类扩展时,会发生一个奇怪的属性。这是代码:

from depot.io.local import LocalFileStorage

class ScriptLocalFileStorage2(LocalFileStorage):

    def create(self, fileid, *args, **kwargs):
        new_file_id = fileid
        content, filename, content_type = self.fileinfo(*args, **kwargs)
        super().__save_file(new_file_id, content, filename, content_type)
        return new_file_id

这是错误:

In [1]: from depot.manager import DepotManager
   ...: DepotManager.configure('scripts2', {'depot.backend': 'app.utils.ScriptLocalFileStorage2', 'depot.storage_path': '/Users/jason/PycharmProjects/sw-edge/app/static/scri
   ...: pts'})
   ...: depot = DepotManager.get('scripts2')
   ...: fileid = depot.create("123fsfl1fdfd3232sfsdfdsff", open('/Users/yinhezhixing/Downloads/simple.txt','rb'))
<app.utils.ScriptLocalFileStorage2 object at 0x113d4aeb8>
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-8438648c61e5> in <module>
      2 DepotManager.configure('scripts2', {'depot.backend': 'app.utils.ScriptLocalFileStorage2', 'depot.storage_path': '/Users/jason/PycharmProjects/sw-edge/app/static/scripts'})
      3 depot = DepotManager.get('scripts2')
----> 4 fileid = depot.create("123fsfl1fdfd3232sfsdfdsff", open('/Users/yinhezhixing/Downloads/simple.txt','rb'))

~/PycharmProjects/sw-edge/app/utils.py in create(self, fileid, *args, **kwargs)
    254         new_file_id = fileid
    255         content, filename, content_type = self.fileinfo(*args, **kwargs)
--> 256         super().__save_file(new_file_id, content, filename, content_type)
    257         return new_file_id

AttributeError: 'super' object has no attribute '_ScriptLocalFileStorage2__save_file'

我希望它创建一个文件ID为“ 123fsfl1fdfd3232sfsdfdsff”的文件,但是发生了未知属性_ScriptLocalFileStorage2__save_file

1 个答案:

答案 0 :(得分:2)

双下划线方法__save_file()受“名称修改”的约束,因为它是“私有”方法,请参见docs here。由于名称修改,您可以看到您实际调用的方法是_ScriptLocalFileStorage2__save_file

通常,您确实应该避免调用私有方法-是否可以使用公共方法代替