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']
  • 相关阅读:
    学生管理系统
    Selenium元素定位的30种方式
    python-- 多进程
    python 多线程的实现
    python 节省内存的for循环技巧
    python 生成器
    python 字符串编码检测
    opencv-python 图片的几何变换
    opencv-python --图像处理
    目标检测
  • 原文地址:https://www.cnblogs.com/yymn/p/5583233.html
Copyright © 2011-2022 走看看