代码之家  ›  专栏  ›  技术社区  ›  cLupus

在Python 3中,如何将变量赋值转换为方法调用?

  •  2
  • cLupus  · 技术社区  · 8 年前

    假设我有以下课程:

    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_NAME , SomeConstants.PROJECT_NAME() , SomeConstants().PROJECT_NAME SomeConstants().PROJECT_NAME() 我得到了相同的结果,即 ProjectConstants 'constants'

    在约翰·库格曼的评论之后,我意识到 一些常量。项目名称 项目常数 ,具有 '常数'

    2 回复  |  直到 8 年前
        1
  •  0
  •   Evan    8 年前

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

        2
  •  0
  •   cLupus    8 年前

    这个 Enum Python中的类实现了我想要的功能。