当前位置:网站首页>反射器中getattr,hasattr,delattr,setattr的使用
反射器中getattr,hasattr,delattr,setattr的使用
2022-07-27 05:22:00 【Leoon123】
反射
把字符串映射到实例的变量或者实例的方法,
然后可以去进行调用、修改操作
反射四个重要的方法:
- 1、getattr 获取对象属性/方法
- 2、hasattr 判断对象是否有对应的属性
- 3、delattr 删除指定属性
- 4、setattr 为对象设置内容
getattr 获取对象属性/方法
class M211Vip:
def welcome(self):
print("恭喜加入组织!!!!!")
def learning(self):
print("正在跟其他人拉开差距......")
没使用getattr前的调用
M211Vip().mylearning()
使用getattr 调用mylearning()方法,不同的是mylearning是字符串
getattr(M211Vip(), "mylearning")()
setattr 为对象设置内容
mylearning为类的外部方法,在M211Vip对象中无法调用,所以需要吧类的外部的函数映射到类里面的方法
class M211Vip:
def welcome(self):
print("恭喜加入组织!!!!!")
def learning(self):
print("正在跟其他人拉开差距......")
def mylearning():
print("正在自学中....")
类的外部的函数映射到类里面的方法
bo = M211Vip()
setattr(bo, "mylearning", mylearning) #先要进行映射,才能使用getattr(bo, "mylearning")() 方法
使用普通的方法调用,或者使用getattr 都可以调用此方法
bo.mylearning()
getattr(bo, "mylearning")()

hasattr 判断对象是否有对应的属性
class M211Vip1:
def __init__(self, name, wkage):
self.name = name
self.wkage = wkage
def welcome(self):
print("恭喜加入组织!!!!!")
def learning(self):
print("正在跟其他人拉开差距......")
bo = M211Vip1("波", "3")
name = getattr(bo, "name") # 把字符串映射到实例的变量
if hasattr(bo, "name"):
print("有name属性....")
else:
print("没name属性....")

delattr删除指定属性
# 4、delattr删除指定属性
delattr(bo, "name")
# print(bo.wkage)
if hasattr(bo, "name"):
print("有name属性....")
else:
print("没name属性....")

边栏推荐
- Unable to start program, access denied?
- 导航相关消息
- 线程安全问题详解
- Unityshader Gaussian blur
- 多线程CAS、synchronized锁原理 、JUC以及死锁
- Wireshark graphical interface capture
- ROS运行管理之launch文件
- The concept of interface testing and the use of postman tools
- Multi threaded CAS, synchronized lock principle, JUC and deadlock
- 5G网络身份识别---详解5G-GUTI
猜你喜欢

Index and transaction of database (emphasis)

Related knowledge of multithreading

Wireshark graphical interface capture

Knowledge supplement of multithreading

PLL of IP core

Li Kou daily question leetcode 513. find the value in the lower left corner of the tree

Remote sensing image recognition imaging synthesis

正则表达式

软件测试基础概念篇

ROS node name duplicate
随机推荐
iptables防火墙及SNAT和DNAT
ROS节点名称重名
Remote sensing image recognition imaging synthesis
5G的前世今生---简述移动通信的发展
C language -- string operation function and memory operation function
bug分类及缺陷和csv文件测试
The concept of interface testing and the use of postman tools
导航相关消息
允许或者禁止同时连接到一个non-domain和一个domain网络
Wireshark packet modification -- adding or modifying message fields (2)
TF coordinate transformation
软件测试基础概念篇
Sexy prime number (acwing daily question)
Wireshark IP address domain name resolution
Summary of test basis
Path to file
DNS故障分析优化
通信机制比较
Programming learning records - Lesson 3 [first knowledge of C language]
技术和理论知识学习的一点心得