首页 > 解决方案 > Python:向实例添加属性,让它出现在类中

问题描述

为了在 Python 中创建与 Matlab 的结构等效的东西,我想创建一个类,该类的设计使得当它的实例被赋予一个整个类还没有的新属性时,该类是自动声明为具有该名称的属性(但动态值)。

例如,如果我color以这种方式定义了类,但没有属性开始,那么我可以执行以下操作:

>> red = color()
>> blue = color()
>> blue.temperature
   AttributeError: type object 'color' has no attribute 'temperature'
>> red.temperature = 'hot'
>> blue.temperature
   blue.temperature = ''
>> blue.temperature = 'cool'

有没有办法破解添加另一个属性的过程并向其添加一个命令,例如cls.x = ''x作为添加到实例的属性名称的变量?

标签: pythonpython-3.xclassattributes

解决方案


以 Octave https://octave.org/doc/v4.4.1/Structure-Arrays.html为例

制作一个结构数组:

>> x(1).a = "string1";
>> x(2).a = "string2";
>> x(1).b = 1;
>> x(2).b = 2;
>>
>> x
x =

  1x2 struct array containing the fields:

    a
    b

如果我将一个字段添加到一个条目,则会为另一个条目添加或定义一个默认值:

>> x(1).c = 'red'
x =

  1x2 struct array containing the fields:

    a
    b
    c

>> x(2)
ans =

  scalar structure containing the fields:

    a = string2
    b =  2
    c = [](0x0)

>> save -7 struct1.mat x

在 numpy

In [549]: dat = io.loadmat('struct1.mat')
In [550]: dat
Out[550]: 
{'__header__': b'MATLAB 5.0 MAT-file, written by Octave 4.2.2, 2019-02-09 18:42:35 UTC',
 '__version__': '1.0',
 '__globals__': [],
 'x': ...

In [551]: dat['x']
Out[551]: 
array([[(array(['string1'], dtype='<U7'), array([[1.]]), array(['red'], dtype='<U3')),
        (array(['string2'], dtype='<U7'), array([[2.]]), array([], shape=(0, 0), dtype=float64))]],
      dtype=[('a', 'O'), ('b', 'O'), ('c', 'O')])
In [552]: _.shape
Out[552]: (1, 2)

该结构已被转换为结构化的 numpy 数组,与shapeOctave相同size(x)。每个结构字段都是dat.

与 Octave/MATLAB 相比,我们无法dat['x']就地添加字段。我认为有一个函数import numpy.lib.recfunctions as rf可以添加一个字段,具有各种形式的屏蔽或未定义值的默认值,但这将创建一个新数组。通过一些工作,我可以从头开始。

In [560]: x1 = rf.append_fields(x, 'd', [10.0])
In [561]: x1
Out[561]: 
masked_array(data=[(array(['string1'], dtype='<U7'), array([[1.]]), array(['red'], dtype='<U3'), 10.0),
                   (array(['string2'], dtype='<U7'), array([[2.]]), array([], shape=(0, 0), dtype=float64), --)],
             mask=[(False, False, False, False),
                   (False, False, False,  True)],
       fill_value=('?', '?', '?', 1.e+20),
            dtype=[('a', 'O'), ('b', 'O'), ('c', 'O'), ('d', '<f8')])
In [562]: x1['d']
Out[562]: 
masked_array(data=[10.0, --],
             mask=[False,  True],
       fill_value=1e+20)

这种动作不太适合 Python 类系统。一个类通常不会跟踪它的实例。并且一旦定义一个类通常不会被修改。可以维护实例列表,也可以向现有类添加方法,但这不是常见的做法。


推荐阅读