python base - reflection of object-oriented programming

The reflecting object-oriented programming

reflection

Definitions: By a string of object properties and methods of operation.

There are four reflection method, are built python, are:

hasattr(obj,name:str)

By "string" property or method of determining the presence or absence of an object . Bool return value , True expressed, False means no.

Note: when query methods, simply write the name of the method, do not add parentheses! ! !

class User:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

    def show_userinfo(self):
        print(f"姓名:{self.name},年龄:{self.age},性别:{self.gender}")


# 创建user对象
user = User("haha", 37, "男")
# 查询属性name 是否存在
res = hasattr(user, "name")
print(res)  # 输出结果:True
# 查询方法show_userinfo 是否存在。注意:不要加括号!!
res_func = hasattr(user, "show_userinfo")
print(res_func)  # 输出结果:True
res_func = hasattr(user, "show_userinfo()")
print(res_func)  # 输出结果:False

getattr(obj,name:str,[default])

By "string" attribute or a method for acquiring an object

note

1. If only the first two parameters passed when the property or method does not exist, an error ;

2. In order to prevent or absence when the attribute, the given method, the third parameter set to the default values can not be found

3. When the acquisition method, do not bring parentheses! ! !

# 创建user对象
user = User("haha", 37, "男")
# 获取属性值
res = getattr(user, "name")
print(res)  # 输出结果:haha
# 获取不存在的属性
res_false = getattr(user, "uid")
print(res_false)  # 报错
# 设置默认值
res_true = getattr(user, "uid", "不存在")
print(res_true)  # 不报错,输出结果:不存在

# 获取方法
res_func = getattr(user, "show_userinfo")
print(res_func)  # 输出结果:方法内存地址
# 获取带括号的方法
func_false = getattr(user, "show_userinfo()")
print(func_false)  # 报错
# 设置默认值
func_true = getattr(user, "show_userinfo()", "不存在")
print(func_true)    # 不报错,输出结果:不存在

setattr(obj,name:str,value)

By "string" attribute set method or object

# 创建user对象
user = User("haha", 37, "男")
# 新增一个属性hobby,属性值是read
setattr(user, "hobby", "read")
print(user.hobby)       # 输出:read
# 修改属性age的值
setattr(user, "age", 27)
print(user.age)         # 输出:27

delattr(obj,name:str)

By "string" property or method to delete objects

note:

Delete nonexistent property or method will complain

When you delete a method, not with parentheses! !

# 创建user对象
user = User("haha", 37, "男")
# 删除属性gender
delattr(user, "gender")
print(user.gender)  # 删除后,输出结果:报错'User' object has no attribute 'gender'
# 删除一个对象没有的属性
delattr(user, "hobby") # 不存在的属性,删除会报错

Guess you like

Origin www.cnblogs.com/xiaodan1040/p/11958274.html