使用type和__slots__创建动态类?

crm*_*key 1 python class dynamic python-2.7

在类中创建结果对象时,是否可以__slots__在此示例中使用?我以为我可以通过传入'__slots__'第三个参数的字典来使它工作type:

class GeocodeResult(object):
    """class to handle Reverse Geocode Result"""

    __slots__ = ['geometry', 'response', 'spatialReference',
                'candidates', 'locations', 'address', 'type', 'results']

    def __init__(self, res_dict, geo_type):
        RequestError(res_dict)
        self.response = res_dict
        self.type = 'esri_' + geo_type
        self.spatialReference = None
        self.candidates = []
        self.locations = []
        self.address = []
        if 'spatialReference' in self.response:
            self.spatialReference = self.response['spatialReference']

        # more stuff

    @property
    def results(self):
        results = []
        for result in self.address + self.candidates + self.locations:
            result['__slots__'] = ['address', 'score', 'location', 'attributes']
            results.append(type('GeocodeResult.result', (object,), result))
        return results

    def __len__(self):
        """get length of results"""
        return len(self.results)
Run Code Online (Sandbox Code Playgroud)

对于results属性,我想构建一个包含4个属性的小型轻量级对象列表:['address', 'score', 'location', 'attributes']

生成的对象已创建,我甚至可以进入插槽,但它仍然保留__dict__.由于可能有数百个结果对象,我只想要上面列出的四个属性来节省空间.

例:

>>> rev = GeocodeResult(r, 'reverseGeocode')
>>> result = rev.results[0]
>>> result.__slots__
['address', 'score', 'location', 'attributes']
>>> hasattr(result, '__dict__')
True
>>> 
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?或者我是否必须定义一个显式类来处理这个问题?

doc*_*red 10

使用插槽动态创建类是完全可能的:

>>> C = type('C', (), {'__slots__': ('a', 'b')})
>>> C.a
<member 'a' of 'C' objects>
>>> dir(C())
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'a', 'b']
>>> vars(C())
Traceback (most recent call last):
  ...
TypeError: vars() argument must have __dict__ attribute
Run Code Online (Sandbox Code Playgroud)

适用于Python 3和2.

您在示例中看到了hasattr(result, '__dict__')evaluate True,因为返回GecodeResult.results的列表是类型列表,而不是实例列表.如果你要说result().__dict__,你会得到一个AttributeError.

(另外值得注意:在列表中的每个类型股份名称"GeocodeResult.result",但他们没有!同一类型results[0].__class__ == results[1].__class__False.)

正如jonrsharpe指出的那样,最好只定义一次类型并重用它,而namedtuple对于这项工作来说是完美的,所以坚持下去:)