本文参考:
https://blog.csdn.net/weixin_42233629/article/details/82261547
https://www.cnblogs.com/zhangjing0502/archive/2012/05/16/2503702.html
getattr()
getattr(object, name[, default])
getattr()用于返回一个类属性(classname.xx)、对象的属性(self.xx)或方法(def xx)的值。
个人理解等同于object.name的效果 第三个参数用于对应属性不存在时作为返回值返回
如下,获取属性或方法的前提是实现一个类,并实例该类
// define a class
class example(object):
def __init__(self):
self.user_name = 'li hua'
def get_user_name(self):
return self.user_name
my_instance = example()
print getattr(my_instance , 'user_name , 'not find')
#如果my_instance 对象中有属性user_name 则打印self.user_name 的值,否则打印'not find'
print getattr(my_instance , 'method', 'default')
#如果有方法method,否则打印其地址,否则打印default
此处如果在getattr()后添加()则会在对象方法存在的情况下执行该方法
print getattr(my_instance , 'method', 'default')()
#如果有方法method,运行函数并打印 None 否则打印default
同时getattr()用于返回类属性时,则无需实例该类
class Foo:
School = 'xihu'
Country = 'China'
language = 'Chiness'
# 方法一,判断用户输入的内容是什么,并输出相关内容
inp = input('>>>')
if inp == 'School': print(Foo.School)
elif inp == 'Country': print(Foo.Country)
elif inp == 'language': print(Foo.language)
# 条件语句每条都打印,非常麻烦,如果有很多条怎么办,用反射实现节省代码量,
# 方法二,用反射的方法
while True:
inp = input('>>>')
if hasattr(Foo, inp): # 判断inp是否为Foo类的静态属性
print(getattr(Foo, inp)) # 获取静态属性,并打印
返回类中的普通函数方法需要python3以上的版本
当类中进行__init__初始化后通过gettattr调用时注意需要传参数
class A:
a = 'Laura'
def __init__(self, name):
self.name = name
def common(self):
print('in common')
print(getattr(A, 'a')) # Laura # 为说明静态属性a可以直接打印,而方法common要加括号执行呢,因为在内存中a直接指向一个值,就是‘Laura’, 而common函数指向一个地址,加括号才可以触发该地址指向的内容执行。
getattr(A, 'common')(1) # in common
同时getattr()可以返回模块或文件中的变量,但由于未做研究此处不作说明解释
setattr()
setattr(object, name, value)
setattr()用于设置一个属性值(字符串name),该值不一定是存在的。
setattr(x,“foobar”,123)相当于x.foobar = 123。
可以理解为添加类的变量
import sys
c = sys.modules['__main__']
class Foo:
a = 'a'
def func():
print('func')
Foo.s = 's' # 通常的添加属性的方法
print(Foo.s) # s
setattr(Foo, 'n', 'n') # 用setattr设置一个属性为n,值为n的变量
print(Foo.n) # n
setattr(Foo, 'n', 'w') # 修改属性的值,所谓设置,就是有此变量时就更改,无此变量时就添加
print(Foo.n) # 'w'
print(Foo.__dict__) # {'__module__': '__main__', 'a': 'a', '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 's': 's', 'n': 'w'}
print(c.__dict__) # {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000146F37772B0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/学习资料/Daily Code and experience/day21 内置方法,反射,登录自动识别身份/反射反射反射.py', '__cached__': None, 'sys': <module 'sys' (built-in)>, 'c': <module '__main__' from 'D:/学习资料/Daily Code and experience/day21 内置方法,反射,登录自动识别身份/反射反射反射.py'>, 'Foo': <class '__main__.Foo'>, 'func': <function func at 0x00000146F372D1E0>}
delattr()
delattr(object, name)
与setattr()相对应的一组函数,参数是由一个对象(记住python中一切皆是对象)和一个字符串组成的。string参数必须是对象属性名之一。该函数删除该obj的一个由string指定的属性。delattr(x, ‘foobar’)=del x.foobar
# delattr() 删除变量
del Foo.Country
print(Foo.__dict__)
delattr(Foo, 'Country') # 格式:(名称空间,‘要删除的变量名’)
delattr(Foo, 'func')
print(Foo.__dict__)
hasattr()
hasattr(object, name) -> bool
用于确定一个对象是否具有某个属性
在getattr()的代码举例中已经出现过。