200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > Python的动态特性(类实例增加属性 动态变量类型)

Python的动态特性(类实例增加属性 动态变量类型)

时间:2021-11-27 06:27:40

相关推荐

Python的动态特性(类实例增加属性 动态变量类型)

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"

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。