zoukankan      html  css  js  c++  java
  • python 内建函数setattr() getattr()

    python 内建函数setattr() getattr()

    setattr(object,name,value):

    作用:设置object的名称为name(type:string)的属性的属性值为value,属性name可以是已存在属性也可以是新属性。

    getattr(object,name,default):

    作用:返回object的名称为name的属性的属性值,如果属性name存在,则直接返回其属性值;如果属性name不存在,则触发AttribetError异常或当可选参数default定义时返回default值。

    <!-- lang: python -->
    >>> class attribute():
    ...     def __init__(self):
    ...             self.attribute_1='i am attribute 1'
    ...             self.attribute_2='i am attribute 2'
    ...
    >>> result=attribute()
    >>> dir(result)
    ['__doc__', '__init__', '__module__', 'attribute_1', 'attribute_2']
    >>> getattr(result,'attribute_1')
    'i am attribute 1'
    >>> getattr(result,'attribute_3')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: attribute instance has no attribute 'attribute_3'
    >>> getattr(result,'attribute_3','i am attribute 3')
    'i am attribute 3'
    >>> dir(result)
    ['__doc__', '__init__', '__module__', 'attribute_1', 'attribute_2']
    >>> getattr(result,'attribute_2')
    'i am attribute 2'
    >>> setattr(result,'attribute_2','i am changed')
    >>> getattr(result,'attribute_2')
    'i am changed'
    >>> setattr(result,'attribute_4','i am new one')
    >>> dir(result)
    ['__doc__', '__init__', '__module__', 'attribute_1', 'attribute_2', 'attribute_4']
  • 相关阅读:
    module 和 component 的区别
    API、SDK、DLL有什么用?
    app基本控件
    PaaS是什么?
    js回调函数(callback)(转载)
    多语言 SEO
    axure rp 8.0
    整天看用户埋点数据,知道数据是咋来的吗?
    发现恶意ip大量访问 可使用命令进行封禁
    阿里云服务器迁移更改IP,导致网站挂掉
  • 原文地址:https://www.cnblogs.com/yymn/p/5583233.html
Copyright © 2011-2022 走看看