当前位置:网站首页>Use of getattr, hasattr, delattr and setattr in reflectors
Use of getattr, hasattr, delattr and setattr in reflectors
2022-07-27 06:39:00 【Leoon123】
Reflection
Mapping strings to instance variables or instance methods ,
Then you can call 、 Modify the operating
There are four important ways to reflect :
- 1、getattr Get object properties / Method
- 2、hasattr Determine whether the object has corresponding attributes
- 3、delattr Delete the specified attribute
- 4、setattr Set content for object
getattr Get object properties / Method
class M211Vip:
def welcome(self):
print(" Congratulations on joining the organization !!!!!")
def learning(self):
print(" Is opening up the gap with others ......")
No use getattr Call before
M211Vip().mylearning()
Use getattr call mylearning() Method , The difference is mylearning Is string
getattr(M211Vip(), "mylearning")()
setattr Set content for object
mylearning Is an external method of a class , stay M211Vip Cannot call , So you need to map the functions outside the class to the methods inside the class
class M211Vip:
def welcome(self):
print(" Congratulations on joining the organization !!!!!")
def learning(self):
print(" Is opening up the gap with others ......")
def mylearning():
print(" In self-study ....")
Functions outside the class map to methods inside the class
bo = M211Vip()
setattr(bo, "mylearning", mylearning) # Map first , Can be used getattr(bo, "mylearning")() Method
Use ordinary method calls , Or use getattr You can call this method
bo.mylearning()
getattr(bo, "mylearning")()

hasattr Determine whether the object has corresponding attributes
class M211Vip1:
def __init__(self, name, wkage):
self.name = name
self.wkage = wkage
def welcome(self):
print(" Congratulations on joining the organization !!!!!")
def learning(self):
print(" Is opening up the gap with others ......")
bo = M211Vip1(" wave ", "3")
name = getattr(bo, "name") # Map the string to the instance variable
if hasattr(bo, "name"):
print(" Yes name attribute ....")
else:
print(" no name attribute ....")

delattr Delete the specified attribute
# 4、delattr Delete the specified attribute
delattr(bo, "name")
# print(bo.wkage)
if hasattr(bo, "name"):
print(" Yes name attribute ....")
else:
print(" no name attribute ....")

边栏推荐
猜你喜欢
随机推荐
2021-06-26
兼容性测试知识点
ROS distributed communication
哈希表简介
Learning records of programming -- Lesson 2 [first knowledge of C language]
Network troubleshooting: Ping and tracert commands
Shell脚本编写格式
DNS域名解析服务
Using markdowm
C language - Custom structure type
C language minesweeping latest recursive expansion super detailed explanation (with source code)
[first blog - outlook]
shell脚本循环
LAMP--源码编译安装
Programming learning records - Lesson 4 [branch and loop statements]
iptables防火墙
shell的编程规范and重定向与管道操作
shell--循环语句(for、while、until)
DHCP principle and configuration
Linu performance tuning: how can we alleviate the situation in the face of DDoS attacks?









