【问题标题】:How may I turn a variable assignment into a methodcall in Python 3?如何在 Python 3 中将变量赋值转换为方法调用?
【发布时间】:2017-09-29 14:59:59
【问题描述】:

假设我有以下课程:

class Constants():
    def __init__(self, constant=None):
        self.value = constant
    # Some magic goes here

class SomeConstants(Constants):
    PROJECT_NAME = 'constants'

如何使该定义以编程方式变为

class SomeConstants(Constants):
    @staticmethod
    def PROJECT_NAME():
        return SomeConstants('constants')

这样每当我调用SomeConstants.PROJECT_NAMESomeConstants.PROJECT_NAME()SomeConstants().PROJECT_NAMESomeConstants().PROJECT_NAME() 时,我都会得到相同的结果,即ProjectConstants 的实例,其值为'constants'

编辑 在 John Kugelman 发表评论后,我意识到调用 SomeConstants.PROJECT_NAME 并获取 ProjectConstants 的实例,并将 'constants' 作为其值将是我正在寻找的。​​p>

【问题讨论】:

  • 你为什么要支持所有这些括号组合而没有括号?这种灵活性的意义何在?这对我来说似乎是一种代码味道。
  • 部分原因是 to 可能被互换使用。想一想,第一种方法最合适,即SomeConstants.PROJECT_NAME

标签: python-3.x metaprogramming


【解决方案1】:

神奇的方法call()可能就是你要找的这里。

【讨论】:

    【解决方案2】:

    Python 中的Enum 类可以满足我的需求。 使用枚举,需要进行一些细微的改动,但就我的意图和目的而言,它解决了问题。

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      相关资源
      最近更新 更多