python反射怎么用

反射: 通过字符串的形式对 对象 进行增删改查

setattr 设置某个属性的值

class A(object):
    def __init__(self):
        self.name = "sath"

    def get(self):
        print("get")


a = A()

setattr(a, "age", 37)
# setattr(object, attribute, value)     ===>    object.attribute = value
print(a.age)
# 37

print(dir(a))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
 '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
 '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
 'age', 'get', 'name']  # 可以发现在a这个对象的空间中新加了一个属性"age"

getattr  获取某个属性的值

class A(object):
    def __init__(self):
        self.name = "sath"

    def get(self):
        print("get")


a = A()

ret = getattr(a, "name", "LaoWang")
getattr(object, "attribute", default)   # 从你那个对象中反射某个属性或方法, 反射不到的话使用默认值
print(ret)
# sath

hasattr  判断是否拥有

class A(object):
    def __init__(self):
        self.name = "sath"

    def get(self):
        print("get")


a = A()

ret = hasattr(a, "name")    # 判断一个对象是否有某个属性或方法, 返回一个布尔值
print(ret)
# True

delattr  删除某个属性

class A(object):
    def __init__(self):
        self.name = "sath"

    def get(self):
        print("get")


a = A()
print(dir(a))
delattr(a, "name")  # 删除对象的某个属性
print(dir(a))

setattr应用实例-restframework中的ModelViewSet

猜你喜欢

转载自www.cnblogs.com/594504110python/p/10184561.html
今日推荐