python 如何从父类重载子类的属性?

源代码:

class FileSaverConf:
    STATIC_DIR = BASE_DIR / 'static'
    FILE_ENCODING = 'utf-8'
    FILE_SUFFIX = ''


class FileSaverConfForAddIndex(FileSaverConf):
    IS_SAVE = False
    STATIC_DIR = FileSaverConf.STATIC_DIR / 'add_index'


class FileSaverConfForSearch(FileSaverConf):
    IS_SAVE = False
    STATIC_DIR = FileSaverConf.STATIC_DIR / 'search'

但是我不想硬编码父类的名字

便下面使用 super() 替代 FileSaverConf 就会报错

class FileSaverConf:
    STATIC_DIR = BASE_DIR / 'static'
    FILE_ENCODING = 'utf-8'
    FILE_SUFFIX = ''


class FileSaverConfForAddIndex(FileSaverConf):
    IS_SAVE = False
    STATIC_DIR = super().STATIC_DIR / 'add_index'


class FileSaverConfForSearch(FileSaverConf):
    IS_SAVE = False
    STATIC_DIR = super().STATIC_DIR / 'search'

报错如下:

File "/Users/bot/Desktop/code/work/python/django/lsh/app.py", line 4, in <module>
    from utils.decorators import save_file
  File "/Users/bot/Desktop/code/work/python/django/lsh/utils/decorators.py", line 3, in <module>
    from conf.settings import (
  File "/Users/bot/Desktop/code/work/python/django/lsh/conf/settings.py", line 12, in <module>
    from .dev_settings import *
  File "/Users/bot/Desktop/code/work/python/django/lsh/conf/dev_settings.py", line 21, in <module>
    class FileSaverConfForAddIndex(FileSaverConf):
  File "/Users/bot/Desktop/code/work/python/django/lsh/conf/dev_settings.py", line 23, in FileSaverConfForAddIndex
    STATIC_DIR = super().STATIC_DIR / 'add_index'
RuntimeError: super(): no arguments
阅读 1.2k
1 个回答

一个你可能不是很喜欢的写法

class FileSaverConf:
    FILE_ENCODING = 'utf-8'
    FILE_SUFFIX = ''

    @classmethod
    @property
    def STATIC_DIR(self):
        return "static/"


class FileSaverConfForAddIndex(FileSaverConf):
    IS_SAVE = False

    @classmethod
    @property
    def STATIC_DIR(self):
        return super().STATIC_DIR + 'search'
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题