回顾一下Pyton中定义类,创建实例
class Student :
def __init__(self,name):
self.name = name
def __str__(self):
return " i am ---> " + self.name
有一个学生 class ,它有一个属性 name
tomc = Student("tom")
print(tomc.name)
生成了一个新的学生对象 ,名字是tom
代码改造一下:获取学生的 id
print(tomc.name)
print(tomc.id)
这时访问id这个属性是不存在的。
如何判断属性不存在的情况呢?hasattr
if hasattr(tomc, "id"):
print(tomc.id)
else:
print(" no attribute ==> ", id)
setattr 给指定属性赋值
tomc = Student("tom")
print(tomc.name)
if hasattr(tomc, "id"):
print(tomc.id)
else:
print(" no attribute ==> ",)
setattr(tomc,"name"," new tom")
print(tomc.name)
- setattr(tomc,"name"," new tom")
- setattr(obj,attributeNameStr, objValue)
给某个对象obj,的某个属性名attributeNameStr,设置一个值objValue
添加一个新的方法
给tomc这个学生增加一个show方法,方法的逻辑是打印一句话
setattr(tomc,"show",lambda :print(" new method"))
tomc.show()
setattr(tomc,"show",lambda :print(" new method"))
tomc.show()
jack = Student("jack")
jack.show()
上面的代码中给tomc动态加了个show方法,而后面的jack没有加这个方法看一下效果,这时会发现jack这个学生找不到 show这个属性的。
delattr删除对象 的属性。
setattr(tomc,"show",lambda :print(" new method"))
tomc.show()
delattr(tomc, "show")
tomc.show()
我拉可以看到在调用 delattr方法后,tomc这个对象就没有办法调用show这个函数了。
在setattr中动态给一个对象添加新属性值
- 这个值可以是任务的Python类型的值,包括函数。 函数与普通类型折值基本一样,唯一 的区别在函数可以被 执行 使用函数名+括号就可以执行了
def a():
pass
print( a ) #函数对象
print( a() ) # 函数执行
改造一下前面的代码
class Student :
def __init__(self,name):
self.name = name
def __str__(self):
return " i am ---> " + self.name
tomc = Student("tom")
print(tomc.name)
if hasattr(tomc, "id"):
print(tomc.id)
else:
print(" no attribute ==> ")
setattr(tomc,"name"," new tom")
print(tomc.name)
lab = lambda :print(" new method")
def show():
print("==show ===")
setattr(tomc,"show",show)
tomc.show()
delattr(tomc, "show")
tomc.show()
setattr(tomc,"show",show)
这个挖槽中 setattr中的第三个参数是一个函数的名字 show
得到的效果与lambda一样