python对象反射和函数反射

030反射,

###反射
## getattr,hasattr,setattr,delattr,和类里面包车型客车字段有关,具体看例子

澳门葡京备用网址 1

#1
class  Person:
    def  __init__(self,name,age):
        self.name = name
        self.age = age
    def  show_lover(self):
        print('lover')

o = Person('x',21)
b = 'name'
print(o.__dict__[b])

# 2 
b = input('>>>')
if  hasattr(o,b):
    v = getattr(o,b)        # 去什么东西里面获取什么内容   
    delattr(o,b)
    setattr(o,'age',21)
print(v)
func=getattr(o,'show_lover')   # 拿到方法
func()

View Code

# 3 得到类对象的字段

class  Person:
    stat = '123'
    def  __init__(self,name,age):
        self.name = name
        self.age = age

r = getattr(Person,'stat')
print(r)

# 4获得其余模块的函数和字段等

# s.py
NAME = '_nbloser'
def  func():
    return'func'
class  Person:
    def  __init__(self):

self.name = '_nbloser'

# 执行.py
import s
r1 = getattr(s,'NAME')
r2 = getattr(s,'func')
Pers = getattr(s,'Person')
p1 = Pers()
print(r1,r2(),p1.name)      # _nbloser   func   _nbloser

 

# 应用小例子

def  f1():
    return'首页'
def  f2():
    return'新闻'
def  f3():
    return'精华'

import  s
inp = input('>>')
if  hasattr(s,inp):
    func = getattr(s,inp)
    print(func())
else:
    print(404)

 

###python对象反射和函数反射。反射 ##
getattr,hasattr,setattr,delattr,和类里面包车型地铁字段有关,具体看例子 # 1
class Person: def __init__ (self,name,age): self.name = name
self.age…

python的对象反射作用,平日在编制程序时使用.相相比较别的的编制程序语言使用极其方便.反射就是用字符串来操作对象可能类,模块中的成员.

###反射
## getattr,hasattr,setattr,delattr,和类里面的字段有关,具体看例子

Python中的反射

Python中的反射和java 等语言的花样分化。

澳门葡京备用网址 2

澳门葡京备用网址 3澳门葡京备用网址 4

举个栗子

class Foo:
    class_file = '123'
    def __init__(self,name,age):
        self.name = name
        self.age = age


obj = Foo('testname',22)
b = 'name'

上边的次序中,制造了多个类 接收七个变量 name 和 age
以后创造了二个Foo的对象,封装了 ‘testname’ 和
22,以往只晓得属性字段是’name’
有未有一种方法能一向得到目的中的name字段对应的性质呢

  • 通过dict
    咱俩通晓dict是放手药方法,该方法以字典的情势再次回到该类定义的所有字段。

print(obj.__dict__['name'])
  • getattr() 获取属性

getattr(obj,name) 为从一个对象中获得属性,那几个指标足以是类对象
能够是模块 也可以是p

print(getattr(obj, b)) # 获取属性
# 获取方法
print(getattr(obj, b))
func = getattr(obj,'show')
r = func()
# 获取类属性
print(getattr(Foo, 'class_file'))
  • hasattr 通过反射判断是不是有有些字段

print(hasattr(obj, b))
  • setattr 通过反射设置有个别属性

setattr(obj,b,'hello')
print(obj.show())
>>> hello-22
  • delattr 通过反射删除属性

delattr(obj,b)
print(obj.show()) # 由于删除了name所以会报错

一.指标的反光

反射功能的达成,由那4个放置函数来贯彻(hasattr, getattr, setattr, delattr)

#1
class  Person:
    def  __init__(self,name,age):
        self.name = name
        self.age = age
    def  show_lover(self):
        print('lover')

o = Person('x',21)
b = 'name'
print(o.__dict__[b])

# 2 
b = input('>>>')
if  hasattr(o,b):
    v = getattr(o,b)        # 去什么东西里面获取什么内容   
    delattr(o,b)
    setattr(o,'age',21)
print(v)
func=getattr(o,'show_lover')   # 拿到方法
func()

1.1.hasattr判断是或不是有某些成员

看清指标中是还是不是有品质, 方法.再次回到bool值

#!/usr/bin/env python # -*-coding:utf-8-*- class Foo(object):
country = “china” def __init__(self, name): self.name = name def
f(self): print “function f” obj = Foo(“abc”) print hasattr(obj, “name”)
#推断是或不是有name字段,再次回到True print hasattr(obj, “f”)
#看清是不是有f方法,重临True print hasattr(obj, “ok”)
#澳门葡京备用网址,一贯不那几个艺术,重临False print hasattr(obj, “country”)
#判别有未有静态字段,重返True print hasattr(Foo, “country”)
#利用类作为参数来决断 print “class:”, Foo.__dict__.keys() print
“obj:”, obj.__dict__.keys()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env python
# -*-coding:utf-8-*-
 
class Foo(object):
    country = "china"
 
    def __init__(self, name):
        self.name = name
 
    def f(self):
        print "function f"
 
obj = Foo("abc")
print hasattr(obj, "name")         #判断是否有name字段,返回True
print hasattr(obj, "f")            #判断是否有f方法,返回True
print hasattr(obj, "ok")           #没有这个方法,返回False
print hasattr(obj, "country")      #判断有没有静态字段,返回True
print hasattr(Foo, "country")      #使用类作为参数来判断
print "class:", Foo.__dict__.keys()
print "obj:", obj.__dict__.keys()

上例中利用对象作为obj参数来剖断,是或不是有类的静态方法.也是能够的.因为对象的特殊性,先在对象中找是不是有该成员,借使没在,通过对象指针,在去创设那一个目的的类中找查

实行结果

True True False True True class: [‘__module__’, ‘f’, ‘country’,
‘__dict__’, ‘__weakref__’, ‘__doc__’, ‘__init__’] obj:
[‘name’]

1
2
3
4
5
6
7
True
True
False
True
True
class: [‘__module__’, ‘f’, ‘country’, ‘__dict__’, ‘__weakref__’, ‘__doc__’, ‘__init__’]
obj: [‘name’]

 

View Code

 1.2.获得对象的成员

也得以动用对象来收获类的成员.和上例中的hasattr同样

#!/usr/bin/env python # -*-coding:utf-8-*- class Foo(object):
country = “china” def __init__(self, name): self.name = name def
f(self): print “this is function = “, self.name obj = Foo(“abc”) print
getattr(obj, “name”) #获取对象的name字段 f = getattr(obj, “f”)
#经过对象得到类的章程 print f #打字与印刷出来是信类的方法 f()
#累加括号就能够一贯调用施行这些的措施 print getattr(Foo, “country”) print
getattr(obj, “country”) #运用对象也能找到静态字段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
# -*-coding:utf-8-*-
 
class Foo(object):
    country = "china"
 
    def __init__(self, name):
        self.name = name
 
    def f(self):
        print "this is function = ", self.name
obj = Foo("abc")
print getattr(obj, "name")             #获取对象的name字段
f = getattr(obj, "f")                  #通过对象获取类的方法
print f                                #打印出来是信类的方法
f()                                    #加上括号就能直接调用执行这个的方法
print getattr(Foo, "country")
print getattr(obj, "country")          #使用对象也能找到静态字段

 

# 3 得到类对象的字段

1.3.增添对象只怕类的分子

动态的扩大对象也许类中的成员

#!/usr/bin/env python # -*-coding:utf-8-*- class Foo(object):
country = “china” def __init__(self, name): self.name = name def
f(self): print “this is function f.name = “, self.name obj = Foo(“abc”)
setattr(obj, “age”, 19) #充实一般性字段 setattr(obj, “show”, lambda num:
num +1) #扩充一般性方法 setattr(Foo, “tel”, “+086”) #充实静态字段 print
obj.age print Foo.tel print obj.show(10)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env python
# -*-coding:utf-8-*-
 
class Foo(object):
    country = "china"
 
    def __init__(self, name):
        self.name = name
 
    def f(self):
        print "this is function f.name = ", self.name
 
 
obj = Foo("abc")
setattr(obj, "age", 19)                       #增加普通字段
setattr(obj, "show", lambda num: num +1)      #增加普通方法
setattr(Foo, "tel", "+086")                   #增加静态字段
print obj.age
print Foo.tel
print obj.show(10)

施行结果

19 +086 11

1
2
3
19
+086
11

 

class  Person:
    stat = '123'
    def  __init__(self,name,age):
        self.name = name
        self.age = age

r = getattr(Person,'stat')
print(r)

1.4.运用delattr动态的删除类也许措施成员

示范代码

#!/usr/bin/env python # -*-coding:utf-8-*- class Foo(object):
country = “china” def __init__(self, name): self.name = name def
f(self): print “this is function f.name = “, self.name obj = Foo(“abc”)
print getattr(obj, “name”) delattr(obj, “name”)
#去除掉了对象的平时字段name print getattr(obj, “name”) print
getattr(Foo, “country”) delattr(Foo, “country”) #删除掉类的静态字段
print getattr(Foo, “country”) #打字与印刷时说找不到些成员,报错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env python
# -*-coding:utf-8-*-
 
class Foo(object):
    country = "china"
 
    def __init__(self, name):
        self.name = name
 
    def f(self):
        print "this is function f.name = ", self.name
 
 
obj = Foo("abc")
print getattr(obj, "name")
delattr(obj, "name")                     #删除掉了对象的普通字段name
print getattr(obj, "name")
print getattr(Foo, "country")
delattr(Foo, "country")                  #删除掉类的静态字段
print getattr(Foo, "country")            #打印时说找不到些成员,报错

实行理并了结果

Traceback (most recent call last): File
“D:/����/python/��������/day08/blog/fanshe.py”, line 17, in
<module> abc print getattr(obj, “name”) AttributeError: ‘Foo’
object has no attribute ‘name’

1
2
3
4
5
Traceback (most recent call last):
File "D:/����/python/��������/day08/blog/fanshe.py", line 17, in <module>
abc
print getattr(obj, "name")
AttributeError: ‘Foo’ object has no attribute ‘name’

 

# 4获得任何模块的函数和字段等

二.在当下模块中运用反射

获得到相应的模块.

#!/usr/bin/env python # -*-coding:utf-8-*- import sys data = “abc”
def f1(): print “f1 function” def f2(): print “f2” this_module =
sys.modules[__name__] print hasattr(this_module, “data”)
#采取反射 f1_get = getattr(this_module, “f1”) #动用反射获取
f1_get()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python
# -*-coding:utf-8-*-
 
import sys
 
data = "abc"
def f1():
    print "f1 function"
def f2():
    print "f2"
 
this_module =  sys.modules[__name__]
print hasattr(this_module, "data")             #使用反射
f1_get = getattr(this_module, "f1")            #使用反射获取
f1_get()

 

以上是反射对类,对象,模块成员操作的主干方法.

 

# s.py
NAME = '_nbloser'
def  func():
    return'func'
class  Person:
    def  __init__(self):

self.name = '_nbloser'

# 执行.py
import s
r1 = getattr(s,'NAME')
r2 = getattr(s,'func')
Pers = getattr(s,'Person')
p1 = Pers()
print(r1,r2(),p1.name)      # _nbloser   func   _nbloser

三.使用字符串自动导入模块

听新闻说传入的字符串,自动导入模块.类似上文的方法反射

import importlib my_moudle_name = “lib.aa” aa =
importlib.import_module(my_moudle_name) print(aa) print(aa.C().name)

1
2
3
4
5
6
7
import importlib
 
my_moudle_name = "lib.aa"
aa = importlib.import_module(my_moudle_name)
 
print(aa)
print(aa.C().name)

实践结果

<module ‘lib.aa’ from ‘D:\\python\\day10\\lib\\aa.py’>
ait24

1
2
<module ‘lib.aa’ from ‘D:\\python\\day10\\lib\\aa.py’>
ait24

 

# 应用小例子

def  f1():
    return'首页'
def  f2():
    return'新闻'
def  f3():
    return'精华'

import  s
inp = input('>>')
if  hasattr(s,inp):
    func = getattr(s,inp)
    print(func())
else:
    print(404)

 

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*
*
Website