标签:hash dict 默认值 __init__ 布尔值 形式 attr str work
反射: 通过字符串的形式对 对象 进行增删改查
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"
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
class A(object): def __init__(self): self.name = "sath" def get(self): print("get") a = A() ret = hasattr(a, "name") # 判断一个对象是否有某个属性或方法, 返回一个布尔值 print(ret) # True
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
标签:hash dict 默认值 __init__ 布尔值 形式 attr str work
原文地址:https://www.cnblogs.com/594504110python/p/10184561.html