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

列出当前存在的所有类

  •  2
  • Soviut  · 技术社区  · 16 年前

    我正在创建一个简单的API,它基于JSON数据创建类型化类,其中定义了一个强制的“type”字段。它使用此字符串定义一个新类型,在JSON对象中添加字段,实例化它,然后填充实例上的字段。

    我想做的是允许在使用我的模块的任何应用程序中可选地预定义这些类型。这样可以添加JSON对象中找不到的方法和其他特定于应用程序的属性。我想让我的模块检查一个类型是否已经存在,如果存在,请使用它,而不是动态创建该类型。它仍然会添加JSON对象的属性,但会回收现有的类型。

    我的JSON数据是:

    {
        "type": "Person",
        "firstName": "John",
        "lastName": "Smith",
        "address": {
            "streetAddress": "21 2nd Street",
            "city": "New York",
            "state": "NY",
            "postalCode": 10021
        },
        "phoneNumbers": [
            "212 555-1234",
            "646 555-4567"
        ]
    }
    

    到目前为止,我的代码(假设json_object此时是一个字典):

    if not json_object.has_key('type'):
        raise TypeError('JSON stream is missing a "type" attribute.')
    
    ##### THIS IS WHERE I WANT TO CHECK IF THE TYPE BY THAT NAME EXISTS ALREADY ####
    # create a type definition and add attributes to it
    definition = type(json_object['type'], (object,), {})
    for key in json_object.keys():
        setattr(definition, key, None)
    
    # instantiate and populate a test object
    tester = definition()
    for key, value in json_object.iteritems():
        setattr(tester, key, value)
    
    3 回复  |  直到 16 年前
        1
  •  1
  •   Adam Rosenfield    16 年前

    如果你想重用之前创建的类型,最好自己缓存它们:

    json_types = {}
    def get_json_type(name):
      try:
        return json_types[name]
      except KeyError:
        json_types[name] = t = type(json_object['type'], (object,), {})
        # any further initialization of t here
        return t
    
    definition = get_json_type(json_object['type'])
    tester = definition()
    # or: tester = get_json_type(json_object['type'])()
    

    如果要将它们添加到模块命名空间中,请执行以下操作

    json_types = globals()
    

    相反。

        2
  •  3
  •   Martin v. Löwis    16 年前

    您可以使用 dir() 要获取当前环境中所有对象的名称列表,您可以使用 globals() 获取一个字典,将这些名称映射到它们的值。因此,要获取类对象的列表,可以执行以下操作:

    import types
    listOfClasses = [cls for cls in globals().values() if type(cls) == types.ClassType]
    
        3
  •  0
  •   Can Berk Güder Pugalmuni    16 年前

    您可以使用 dir() :

    Python 2.5.2 (r252:60911, Oct  5 2008, 19:29:17)
    [GCC 4.3.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> dir()
    ['__builtins__', '__doc__', '__name__']
    >>> class Foo:
    ...     pass
    ...
    >>> dir()
    ['Foo', '__builtins__', '__doc__', '__name__']
    >>> type(eval('Foo'))
    <type 'classobj'>