Python 中的动态对象,如 AS3 中的动态对象
在AS3中,我们有一个关键字来定义动态对象:
dynamic class DynamicClass { ... }
因此,我们可以在运行时添加或删除属性。
var dynamicInstance:DynamicClass = new DynamicClass();
// add a property like this...
dynamicInstance.newProperty = 'newValue';
// or this...
dynamicInstance['otherProperty'] = 'otherValue';
我可以访问甚至迭代整个动态属性集合:
for (var name:String in dynamicInstance)
trace(name, '=', dynamicInstance[name])
// output:
// newProperty = newValue
// otherProperty = otherValue
而且我还可以删除这些属性:
// and delete a property like this...
delete dynamicInstance.newProperty;
// or this...
delete dynamicInstance['otherProperty'];
如何在 Python 中做到这一点?
In AS3 we have a keyword to define dynamic objects:
dynamic class DynamicClass { ... }
So, we can add or delete properties in run-time.
var dynamicInstance:DynamicClass = new DynamicClass();
// add a property like this...
dynamicInstance.newProperty = 'newValue';
// or this...
dynamicInstance['otherProperty'] = 'otherValue';
The I can acces or even iterate throught the whole collection of dynamic properties:
for (var name:String in dynamicInstance)
trace(name, '=', dynamicInstance[name])
// output:
// newProperty = newValue
// otherProperty = otherValue
And I also can delete those properties:
// and delete a property like this...
delete dynamicInstance.newProperty;
// or this...
delete dynamicInstance['otherProperty'];
How can this be done in Python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
python中的所有类都是动态的。你可以像这样访问它们
或
如果你想更改类的所有实例,你可以轻松编写一个for循环来忽略以__开头的实例
all classes in python are dynamic. you can acces them like this
or
If you want to change all instances of the class you can easily write a for loop that ignors the instances starting with __
一位同事就此给了我建议,我们找到了解决方案:
这是一个测试:
A co-worker gave me an advice on this and we found a solution for this:
Here is a test: