简体   繁体   English

在 class __init__ 中将嵌套枚举值设置为默认参数

[英]Setting nested enum value as default parameter in class __init__

I have a nested enum which holds two possible value for a parameter of a class.我有一个嵌套枚举,它为 class 的参数保存两个可能的值。 I would like to give on enum as the default value for the class in the __init__我想将枚举作为__init__中 class 的默认值

Something that would look like that:看起来像这样的东西:

from enum import IntEnum as IntEnum
class A:
    class AParam(IntEnum):
        TYPE_1 = 1
        TYPE_2 = 2
    def __init__(self, param=A.AParam.TYPE_1):
        self.param = param

Of course It dosen't work, I guess because the class is not fully constructed yet.当然它不起作用,我猜是因为 class 尚未完全构建。

The alternative solution I'm doing right now is this:我现在正在做的替代解决方案是:

from enum import IntEnum as IntEnum
class A:
    class AParam(IntEnum):
        TYPE_1 = 1
        TYPE_2 = 2

    def __init__(self, param=None):
        if param is None:
            param = A.AParam.TYPE_1
        self.param = param

For several reasons, I don't want to use strings instead of enums.出于几个原因,我不想使用字符串而不是枚举。 I could use also not put the parameter in the init , and just let the class user use the member variable itself.我也可以不将参数放在init中,而让 class 用户使用成员变量本身。 But then the default parameter is not so explicit.但是默认参数不是那么明确。

Is there another way of passing nested enum as default value for the __init__ method?是否有另一种将嵌套枚举作为__init__方法的默认值传递的方法? Or is that just not possible...?或者那是不可能的……?

You can regard the inside of the class as a scope, not unlike the scope inside a function.您可以将 class 的内部视为 scope,与 ZC1C425268E683985D1AB504F 内部的 scope 不同。

Therefore, you can do this:因此,您可以这样做:

class A:

    class AParam(IntEnum):
        TYPE_1 = 1
        TYPE_2 = 2

    def __init__(self, param=AParam.TYPE_1):
        self.param = param

Note the missing A. .注意缺少的A. .

This scope is active during the definition of the contents of the class.在定义 class 的内容期间,此 scope 处于活动状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM