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
就会报错
python">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
回答:
一个你可能不是很喜欢的写法
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'
以上是 python 如何从父类重载子类的属性? 的全部内容, 来源链接: utcz.com/p/938113.html