python - 在Python中扩展内部类属性

标签 python django

在我的 django 应用程序中,有几个应用程序是通过 apps.py 文件激活 AppConfig 的,并且我有一个 BaseAppConfig 类:

class BaseAppConfig(AppConfig):
    launchpad = None

    def __init__(self, app_name, app_module):
        AppConfig.__init__(self, app_name, app_module)
        self.launchpad = self.Launchpad()

    class Launchpad:
        show = True
        icon = "fa fa-cogs"

我在我的自定义应用程序中使用这个BaseAppConfig,例如:

class CustomerConfig(BaseAppConfig):
    name = 'customer'

    class Launchpad:
        icon = "fa fa-book"

当我尝试使用 customer_config.launchpad.show 访问 CustomerConfigshow 属性时,它返回 AttributeError

Python 会像 new 一样重写所有内部类。

如何实现仅扩展内部类的属性?

最佳答案

这是因为您正在重写 Launchpad 类。因此,它无法按照您的意愿回退并解析为 BaseAppConfig

您需要将您的类(class)更改为此才能使其正常工作,

class CustomerConfig(BaseAppConfig):
     name = 'customer'

    class Launchpad(BaseAppConfig.Launchpad):
        icon = "fa fa-book"

这样它就可以引用基类 Launchpad 实例。

关于python - 在Python中扩展内部类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51334196/

相关文章:

javascript - 将javascript json对象转换为字符串

django - 带有soaplib的Django中的SOAP服务

Django 服务器推送方法

python - 如果从不同的 View 函数调用,则不会传递上下文数据

python - nginx.service : Failed to read PID from file/run/nginx. pid : Invalid argument ubuntu 16. 04 xenial

python - Django:两个字段组成一个键?

python - Pylance 在 VSCode Jupyter 笔记本中不起作用

python - 值错误: Location based indexing can only have [labels (MUST BE IN THE INDEX)

python - HDFStore 附加错误 - "Cannot serialize the column"

python - 丢弃数据报套接字的传入 'packets'