Python类实例具有动态特性:它们是在运行时创建的,可以在创建后进一步修改。
例如: 给对象动态添加一个属性:
p1.__setattr__('aaa', 'hahhah')
检测一个对象是否含有某个属性:
hasattr(p1, 'aaa')
获取对象的某个属性,不存在则返回默认值(而不是抛异常):
getattr(p1, 'aaa', 'default value')
另外,Python是一种动态类型语言,Python解释器在初始化操作对象之前不需要知道它们的类型。由于此属性,以下代码段被认为是有效的。Python being a dynamically typed language, the Python interpreter does notneedto know the type of the manipulated objects before their initialisation. Thanks to this property, the following code snippet is consideredvalid.
def do_i_want_an_int():# Complex and long computationsreturn computation_is_successif do_i_want_an_int():a = 1else:a = "I'm a string"