Application scenarios of setattr\getattr\delattr\hasattr

1. setattr description

The setattr() function corresponds to the function getattr(), which is used to set the attribute value, and the attribute does not necessarily exist.

Syntax: setattr(object, name, value)
object – object.
name – string, object property.
value – the attribute value.

2. getattr description

The getattr() function is used to return an object attribute value.

getattr Syntax: getattr(object, name[, default])
object – object.
name – string, object property.
default – The default return value. If this parameter is not provided, AttributeError will be triggered if there is no corresponding attribute.

3. delattr description

The delattr function is used to delete attributes. delattr(x, 'foobar') is equivalent to del x.foobar.

delattr Syntax: delattr(object, name)
object – object.
name – must be a property of the object.

4. hasattr description

The hasattr() function is used to determine whether the object contains the corresponding attribute.

hasattr Syntax: hasattr(object, name)
object – object.
name – string, property name.

5. Application scenarios (mainly setattr)

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time

'''setattr含义:为一个类设置属性或值-setattr(class, attribute, value),即使这个属性不存在
应用场景:
场景1、初始化未必全需要写在def __init__(self)函数里面。如果有很多的话写起来会比较长。可以通过下面代码init_fun拆分。
场景2、可以动态添加属性,增加类或实例的添加属性的灵活性。
场景3、当批量初始化同样的属性时,可以减少代码量。
场景4、可以当作错误码使用。
上述场景在下面代码里面也会涉及到。
'''


class A(object):
    def __init__(self):
        # 场景1
        self.init_fun()

    # 场景3
    def add_attribute(self, attribute, room_size, des, price):
        value = {
    
    "room_size": room_size,
                 "description": des,
                 "price": price}
        setattr(self, attribute, value)

    # 场景3(将add_attribute里面的数据改成web的错误码集合,就能应用到场景4)
    def init_fun(self):
        self.add_attribute("roomA", "100", "high", "10w")
        self.add_attribute("roomB", "130", "low", "15w")
        self.add_attribute("roomC", "140", "low", "100w")
        self.add_attribute("roomD", "150", "low", "10w")


test = A()
print(test.roomA)
# 场景2
setattr(test, "roomE", {
    
    "room_size": "100",
                        "description": "middle",
                        "price": "90W"})
print(test.roomE)
# getattr的用法
print(getattr(test, "roomB"))
# delattr的用法
print(delattr(test, "roomB"))
# hasattr的用法
print(hasattr(test, "roomB"))
print(hasattr(test, "roomA"))

The output is as follows:

E:\pythonPrj\common\venv\Scripts\python.exe E:/pythonPrj/common/setattr_getattr.py
{
    
    'room_size': '100', 'description': 'high', 'price': '10w'}
{
    
    'room_size': '100', 'description': 'middle', 'price': '90W'}
{
    
    'room_size': '130', 'description': 'low', 'price': '15w'}
None
False
True

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/eettttttt/article/details/131447697