Python 如何从包含类定义的.py文件中获取属性名

Python 如何从包含类定义的.py文件中获取属性名,python,python-2.7,Python,Python 2.7,我得到的输入文件只包含一个类定义(类只是常量容器,包含json的键,类似的文件在Java客户端上用于解码json)如下所示: class Constants(object): VERSION= 'version' OS = 'os' PROGRAM = 'program' # more constants ..... 如何获取常量中定义的所有属性的字典,如何将文件解析为字典? 我想压缩键并生成新的.py和.java文件,这些文件的常量键相同,但键较短 >

我得到的输入文件只包含一个类定义(类只是常量容器,包含json的键,类似的文件在Java客户端上用于解码json)如下所示:

class Constants(object):

    VERSION= 'version'
    OS = 'os'
    PROGRAM = 'program'
    # more constants .....
如何获取常量中定义的所有属性的字典,如何将文件解析为字典? 我想压缩键并生成新的.py和.java文件,这些文件的常量键相同,但键较短

>>> [elem for elem in dir(Constants) if not elem.startswith("_")]
['OS', 'PROGRAM', 'VERSION']
  • 导入模块
    • 在下面的代码中,我使用而不是
      \uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
      来导入二进制文件路径
  • 查找类对象
  • 使用以下命令迭代类属性:

  • 在2.7.6、3.3.2、3.4.0b2上用Python进行测试

  • 导入模块
    • 在下面的代码中,我使用而不是
      \uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
      来导入二进制文件路径
  • 查找类对象
  • 使用以下命令迭代类属性:


  • 在2.7.6、3.3.2、3.4.0b2上用Python进行测试。

    扩展答案1:

    # dir(yourClass) will get you all the methods and properties of yourClass and parents wheather yourClass
    # is a definition or an instance
    elements = [elem for elem in dir(Constants) if not elem.startswith("_")]
    
    # Using yourClass.__dict__.keys() will give you the same of dir if applied to a definition but only instance members 
    # if applied to an instance
    elements = [elem for elem in Constants.__dict__.keys() if not elem.startswith("_")]
    
    # You can get to the values of the properties with
    for el in elements:
        print Constants.__dict__[el]
        # plus whatever you want to do to those elements
    
    # Or if you're using the __dict__ way
    Constants.__dict__.items()
    

    扩展答案一:

    # dir(yourClass) will get you all the methods and properties of yourClass and parents wheather yourClass
    # is a definition or an instance
    elements = [elem for elem in dir(Constants) if not elem.startswith("_")]
    
    # Using yourClass.__dict__.keys() will give you the same of dir if applied to a definition but only instance members 
    # if applied to an instance
    elements = [elem for elem in Constants.__dict__.keys() if not elem.startswith("_")]
    
    # You can get to the values of the properties with
    for el in elements:
        print Constants.__dict__[el]
        # plus whatever you want to do to those elements
    
    # Or if you're using the __dict__ way
    Constants.__dict__.items()
    

    下面是一个使用
    execfile
    和Python2.6(我处理Debian Wheezy)的示例。还提供了一个用于为python 2.7版及更高版本构建字典的较短版本。
    constants.py
    文件可以定义几个类,所有类都将被解析

    #!/usr/bin/env python
    
    d = {}
    const_d = {}
    
    execfile("constants.py", d)
    
    for k,cls in d.items():
      if k not in vars(__builtins__):
        if type(cls) is type:
          # Python version < 2.7
          attributes = {}
          for name, value in vars(cls).items():
            if not name.startswith('__'):
              attributes[name] = value
          # Python version >= 2.7
          #attributes = {name: value for name, value in vars(cls).items() if not name.startswith('__')}
          const_d[cls.__name__] = attributes
          pass
        pass
      pass
    
    print(const_d)
    
    #/usr/bin/env python
    d={}
    常数d={}
    execfile(“constants.py”,d)
    对于k,d.items()中的cls:
    如果k不在VAR中(内置):
    如果类型(cls)为类型:
    #Python版本<2.7
    属性={}
    对于名称,变量(cls)中的值。项()
    如果不是name.startswith(“”“”):
    属性[名称]=值
    #Python版本>=2.7
    #attributes={name:name的值,vars(cls)中的值。items()如果不是name.startswith('''.'')}
    常数d[cls.\uuuuu name\uuuuuu]=属性
    通过
    通过
    通过
    打印(常数)
    
    下面是一个使用
    execfile
    和python 2.6(我在Debian Wheezy上工作)的示例。还提供了一个用于为python 2.7版及更高版本构建字典的较短版本。
    constants.py
    文件可以定义几个类,所有类都将被解析

    #!/usr/bin/env python
    
    d = {}
    const_d = {}
    
    execfile("constants.py", d)
    
    for k,cls in d.items():
      if k not in vars(__builtins__):
        if type(cls) is type:
          # Python version < 2.7
          attributes = {}
          for name, value in vars(cls).items():
            if not name.startswith('__'):
              attributes[name] = value
          # Python version >= 2.7
          #attributes = {name: value for name, value in vars(cls).items() if not name.startswith('__')}
          const_d[cls.__name__] = attributes
          pass
        pass
      pass
    
    print(const_d)
    
    #/usr/bin/env python
    d={}
    常数d={}
    execfile(“constants.py”,d)
    对于k,d.items()中的cls:
    如果k不在VAR中(内置):
    如果类型(cls)为类型:
    #Python版本<2.7
    属性={}
    对于名称,变量(cls)中的值。项()
    如果不是name.startswith(“”“”):
    属性[名称]=值
    #Python版本>=2.7
    #attributes={name:name的值,vars(cls)中的值。items()如果不是name.startswith('''.'')}
    常数d[cls.\uuuuu name\uuuuuu]=属性
    通过
    通过
    通过
    打印(常数)
    
    @thefourtheye:
    如何获取常量中定义的所有属性的字典
    。我的回答是基于这一陈述的。否则,他只需要几条语句,就可以读取模块内的所有类,然后递归地确定所有properties@thefourtheye:
    如何获取常量中定义的所有属性的字典
    。我的回答是基于这一陈述的。否则,他需要更多的语句来读取模块中的所有类,然后递归地确定所有属性这里没有在常量中定义属性,这些都是常规属性。您可能最好使用模块。在常量中没有定义属性,这些都是常规属性。您最好使用该模块。