文章目录
一、反射概念
- 通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法:
- getattr(__o, name, __default)
- hasattr(__object, __name)
- setattr(__obj, __name, __value)
- delattr(__obj, __name)
二、反射方法详解
1. hasattr(__object, __name)
- Return whether the object has an attribute with the given name.
- 判断对象是否有指定方法或属性
hasattr(__object, __name) 参数详解:
- __object:
- 对象名
- __name:
- 方法名
- 实例变量名
- 类变量名
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
class Cat(object):
cat_type = "Meiduan"
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self, food):
print("%s is eating... %s" % (self.name, food))
if __name__ == '__main__':
cat = Cat("Huajuan", 2)
# 检查方法名
print(hasattr(cat, "eat"))
# 检查实例变量
print(hasattr(cat, "name"))
print(hasattr(cat, "age"))
# 检查类变量
print(hasattr(cat, "cat_type"))
# 检查没有的属性, 猫咪重量cat_weight
print(hasattr(cat, "cat_weight"))
# 输出:
True
True
True
True
False
2. getattr(__o, name, __default)
- Get a named attribute from an object; getattr(x, ‘y’) is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn’t
exist; without it, an exception is raised in that case.- 主要用于调用函数/变量;
getattr(__o, name, __default) 参数详解:
- __o:
- 对象名
- name:
- 方法名
- 实例变量名
- 类变量名
- __default:
- getattr(x, ‘y’) 调用时:如果指定name的1. 方法名、 2. 实例变量名、3. 类变量名均不存在,则会产生异常AttributeError;
- getattr(x, ‘y’, ‘Mason’) 调用时:如果指定name的1. 方法名、 2. 实例变量名、3. 类变量名均不存在,则会返回__default中给定值;
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
class Cat(object):
cat_type = "Meiduan"
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self, food):
print("%s is eating... %s" % (self.name, food))
if __name__ == '__main__':
cat = Cat("Huajuan", 2)
# 调用类中方法
getattr(cat, "eat")(cat)
# 调用实例变量
print(getattr(cat, "name"))
print(getattr(cat, "age"))
# 调用类变量
print(getattr(cat, "cat_type"))
# getattr调用时传__default, __default可以是方法、可以是任意数据类型数据, 此处以字符串为例
print(getattr(cat, "cat_weight", "5kg"))
# 如果不传__default参数, 且传的name在类中不存在, 则会产生异常AttributeError
print(getattr(cat, "cat_weight"))
# 输出:
Huajuan is eating... <__main__.Cat object at 0x000002503E29CFD0>
Huajuan
2
Meiduan
5kg
Traceback (most recent call last):
File "D:\Codes\s14_python3\oop_learning.py", line 30, in <module>
print(getattr(cat, "cat_weight"))
AttributeError: 'Cat' object has no attribute 'cat_weight'
3. setattr(__obj, __name, __value)
- setattr(x, ‘y’, v) is equivalent to "x.y = v’’;
- 主要用于设置函数/变量;
setattr(__obj, __name, __value)参数详解:
- __obj:
- 对象名
- __name:
- 方法名
- 实例变量名
- 类变量名
- __value:
- 具体函数/变量值;
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
class Cat(object):
cat_type = "Meiduan"
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self, food):
print("%s is eating... %s" % (self.name, food))
if __name__ == '__main__':
cat = Cat("Huajuan", 2)
# 查看当前对象是否有"cat_weight"属性
print(hasattr(cat, "cat_weight"))
# 使用setattr设置cat_weight属性
setattr(cat, "cat_weight", "5kg")
# 查看当前对象是否有"cat_weight"属性
if hasattr(cat, "cat_weight"):
# 使用getattr调用cat_weight属性
print(getattr(cat, "cat_weight"))
# 输出:
False
5kg
4. delattr(__obj, __name)
- delattr(x, ‘y’) is equivalent to "del x.y’’;
- 主要用于删除函数/变量;
delattr(__obj, __name)参数详解:
- __obj:
- 对象名
- __name:
- 方法名
- 实例变量名
- 类变量名
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Mason
class Cat(object):
cat_type = "Meiduan"
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self, food):
print("%s is eating... %s" % (self.name, food))
if __name__ == '__main__':
cat = Cat("Huajuan", 2)
# 调用当前对象的"name"属性
print(getattr(cat, "name"))
# 删除当前对象的"name"属性
delattr(cat, "name")
# 再次调用当前对象的"name"属性, 由于已经删除name属性, 所以会报AttributeError异常
print(getattr(cat, "name"))
# 输出:
Traceback (most recent call last):
File "D:\Codes\s14_python3\oop_learning.py", line 25, in <module>
print(getattr(cat, "name"))
AttributeError: 'Cat' object has no attribute 'name'
Huajuan