python - 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
作为添加到实例的属性名称的变量?
解决方案
以 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 数组,与shape
Octave相同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 类系统。一个类通常不会跟踪它的实例。并且一旦定义一个类通常不会被修改。可以维护实例列表,也可以向现有类添加方法,但这不是常见的做法。
推荐阅读
- javascript - 内部 DIV 滚动/滑动到它们所在的 DIV 的顶部
- sql - 如何采用按单独列排序的 DISTINCT ON 子查询并使其快速?
- java - 无法对mysql数据库进行记录,数据从html和js文件传递到java类
- ios - ImagePicker 和分配给 ImageView 的问题
- wordpress - 如何按元值订购我的 WP 查询,并且只从不同的元中获取某些值?
- vue.js - 在 Vue-CLI 中使用 PleaseWait.js 加载屏幕
- python - 如何在 BaggingClassifier 中调整 SVM 的参数
- reporting-services - 带有新条目的 SSRS 订阅电子邮件
- javascript - 将其中包含数字数组的字符串转换为实际值
- javascript - 如何改进 div 的这种 Javascript 切换?