zoukankan      html  css  js  c++  java
  • Python内置函数(57)——setattr

    英文文档:

    setattr(object, name, value)

    This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123

    说明:

      1. setattr函数和getattr函数是对应的。一个设置对象的属性值,一个获取对象属性值。

      2. 函数有3个参数,功能是对参数object对象,设置名为name的属性的属性值为value值。

    >>> class Student:
        def __init__(self,name):
            self.name = name
    
            
    >>> a = Student('Kim')
    >>> a.name
    'Kim'
    >>> setattr(a,'name','Bob')
    >>> a.name
    'Bob'

      3. name属性可以是object对象的一个已经存在的属性,存在的话就会更新其属性值;如果name属性不存在,则对象将创建name名称的属性值,并存储value值。等效于调用object.name = value。

    >>> a.age # 不存在age属性
    Traceback (most recent call last):
      File "<pyshell#20>", line 1, in <module>
        a.age
    AttributeError: 'Student' object has no attribute 'age'
    
    >>> setattr(a,'age',10) # 执行后 创建 age属性
    >>> a.age  # 存在age属性了
    10
    >>> a.age = 12 # 等效于调用object.name
    >>> a.age
    12
  • 相关阅读:
    codeforces-1194 (div2)
    单链表1(悲剧文本)
    迷宫(深度搜索)
    皇后问题
    关键路径
    [NOI2015]软件包管理器
    [USACO13JAN]岛游记Island Travels
    仓鼠找sugar
    [SHOI2012]魔法树
    [HEOI2016/TJOI2016]树
  • 原文地址:https://www.cnblogs.com/sesshoumaru/p/6063893.html
Copyright © 2011-2022 走看看