在Python中,如何从类方法的返回值初始化类属性?

Ad *_*d N 3 python class python-3.x

想象一下,我们有这个课程:

class Custom:
    @classmethod
    def get_choices(cls):
        # use cls attributes to return a list

    mapping = {"key": ... }
Run Code Online (Sandbox Code Playgroud)

我想返回的值相关联get_choices()key.应该使用什么代码而不是占位符... ?


编辑:我想保持与上下文无关的问题(在我看来,这个要求很常见,但我可能有偏见).正如评论中所建议的那样,我将提供更多细节,因为我们似乎共同关注"最直接的代码":

我正在研究一个Django应用程序,我希望使用它们来保存枚举值的Models.在我看来,像一个自然的解决方案是创建一个enumeration.py模块,然后我可以class为每个枚举定义一个(该类至少有一个类方法来生成值集合).这是get_choices()示例中的内容.

现在,由于业务逻辑,我需要将这些选择映射到密钥.这个映射在逻辑上耦合到枚举,在同一个类中保持它们在一起似乎是一个很好的结构(给客户端代码统一和显式访问,以类名为前缀).

hsp*_*her 6

您无法在类定义中执行此操作,因为尚未创建类对象.在课程定义之后,你绝对可以做到这样的事情 -

Custom.mapping['key'] = Custom.get_choices()
Run Code Online (Sandbox Code Playgroud)

虽然推荐的方法是使用元类.

class CustomMetaClass(type):

      def __init__(cls, classname, bases, attrs):
          super(CustomMetaClass, cls).__init__(classname, bases, attrs)

          cls.mapping['key'] = cls.get_choices()

class Custom(metaclass = CustomMetaClass): # assuming you are using python 3

      mapping = {}

      @classmethod
      def get_choices(cls):
          # add your custom code here
          pass
Run Code Online (Sandbox Code Playgroud)

话虽如此,这是一个面向对象的问题解决方案.您可以使用某些函数来生成选择,从而结束使用元类的需要.

编辑问题: -

在这种情况下,我认为您应该按照自己的建议维护一个名为"choices.py"的文件,并在映射中使用它们,而不是get_choices类方法.如果你想做的只是商店选择,你不需要为每个模型不必要地创建类.只需使用dicts和常量.

如果你的类需要动态生成,比如db,那么你需要创建单独的模型来存储选择.

class CustomModelChoices(models.Model):

      model_name = models.StringField(db_field = 'mn')
      choices = models.DictField(db_field = 'ch')

class CustomModel(models.Model):

     _choice_generator = CustomModelChoices

     mapping = {
         'key': CustomModelChoices.objects.get(model_name = 'CustomModel').choices
     }
Run Code Online (Sandbox Code Playgroud)

这只是一个原始设计,可能需要进行很多改进,但在这些方面有所改进.

  • 对不起Shaktimaan (2认同)