Python中的动态对象,如AS3中的

时间:2011-03-30 14:56:43

标签: python actionscript-3 object dynamic

在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中完成?

2 个答案:

答案 0 :(得分:4)

python中的所有类都是动态的。你可以像这样访问它们

class a:
   pass

>>> a.name="rob"
>>> a.age=45
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__',
 '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__',
 '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
 '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name']

>>> a.age
45
>>> a.name
'rob'

>>> setattr(a,"job","fischer")
>>> getattr(a,"name")
'rob'

如果要更改类的所有实例,可以轻松编写一个忽略以__

开头的实例的for循环

答案 1 :(得分:1)

一位同事给了我一个建议,我们找到了解决方案:

class Dynamic:
    def __getitem__(self, name):
        return getattr(self, name)

    def __setitem__(self, name, value):
        setattr(self, name, value)

    def __delitem__(self, name):
        delattr(self, name)

    def __iter__(self):
        return self.__dict__.__iter__()

这是一个测试:

dynamicInstance = Dynamic()
dynamicInstance.newProperty = 'newValue'
dynamicInstance['otherProperty'] = 'otherValue'

print [(name, dynamicInstance[name]) for name in dynamicInstance]

del dynamicInstance['newProperty']

print [(name, dynamicInstance[name]) for name in dynamicInstance]

del dynamicInstance.otherProperty

print [(name, dynamicInstance[name]) for name in dynamicInstance]

#output:
# [('otherProperty', 'otherValue'), ('newProperty', 'newValue')]
# [('otherProperty', 'otherValue')]
# []