美文网首页
Python内置函数 setattr()

Python内置函数 setattr()

作者: 村东头老骥 | 来源:发表于2019-10-08 15:43 被阅读0次

Python setattr() 函数

setattr() 函数对应函数 getattr(),用于设置属性值,该属性不一定是存在的。

语法

setattr(object, name, value)
  object -- 对象。
  name -- 字符串,对象属性。
  value -- 属性值。

举例说明

class Bar(object):

    def __init__(self):
        pass

bar = Bar()  # 实例化

print(dir(bar))  # 比较两次的属性
setattr(bar, "name", "测试")   # 通过 setattr 的方法给 实例化 bar 对象设置属性
print(dir(bar))  # 比较两次的属性
print(bar.name)  # 测试

# 在次实例化一个对象 bar2 
bar2 = Bar()
print(bar2.name)  # 程序会报错 
# AttributeError: 'Bar' object has no attribute 'name'

Python getattr() 函数

getattr() 函数用于返回一个对象属性值。

语法

getattr(object, name[, default])
  object -- 对象。
  name -- 字符串,对象属性。
  default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。

举例说明

class Foo(object):
    name = "测试"
    def __init__(self):
        pass

foo = Foo()
print(getattr(foo, "name"))  # 测试
print(getattr(foo, "name2", "暂无属性,异常发生"))  # 测试

Django CBV 对应源码

关于 setattr 的方法的使用

class View:
    """
    Intentionally simple parent class for all views. Only implements
    dispatch-by-method and simple sanity checking.
    """

    http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

    def __init__(self, **kwargs):
        """
        Constructor. Called in the URLconf; can contain helpful extra
        keyword arguments, and other things.
        """
        # Go through keyword arguments, and either save their values to our
        # instance, or raise an error.
        for key, value in kwargs.items():
            setattr(self, key, value)

编写MyViews

class MyViews(View):
      # 可以设置自己需要的属性值 源码中存在  setattr(self, key, value)
      key = value
      def get(self,request):
          self.key # 获取设置的属性
# 写的比较仓促,简陋...望见谅! ! !

相关文章

网友评论

      本文标题:Python内置函数 setattr()

      本文链接:https://www.haomeiwen.com/subject/bqiiyctx.html