反射とは何ですか?
文字列データ型の変数名を使用して、この変数の値にアクセスします
反射法:計4つ
- getattr指定された文字列名のオブジェクト属性を取得します
- hasattrオブジェクトに対応するオブジェクトがあるかどうかを判別(文字列)
- setattrはオブジェクトのオブジェクトを設定します
- delattrは指定された属性を削除します
主に反射はどこで使用されますか?
- クラス
- 対象
- モジュール
- モジュール
のリフレクションの概念にリフレクションの概念があるのはなぜですか?
fun1、fun2、fun3と呼ばれる3つの関数があります。これらの関数の1つを呼び出したい場合は、コードでのみ記述します。たとえば、この関数を実現するために次のようなコードを記述しました。
スパイ
def func1():
return "func1"
def func2():
return "func2"
def func3():
return "func3"
test.py
import s
call_str = input("input which function you want to call:")
if call_str == 'func1':
print(s.func1())
elif call_str == 'func2':
print(s.func2())
elif call_str == 'func3':
print(s.func3())
else:
print("404 NOT Found")
考えてみてください。sモジュールに呼び出す関数が数千ある場合は、test.pyに数千の判断ステートメントを記述する必要があります。これは面倒です。
このとき、反映メカニズムが導入されました。
反射メカニズムを追加します。
import s
call_str = input("input which function you want to call:")
"""
if call_str == 'func1':
print(s.func1())
elif call_str == 'func2':
print(s.func2())
elif call_str == 'func3':
print(s.func3())
else:
print("404 NOT Found")
"""
obj = getattr(s,call_str)
print(obj())
実行後、fun1、fun2、fun3を入力できますが、文字列をランダムに入力すると、getattrの組み込み関数が次のエラーを報告します。
このとき、hasattrの組み込み関数を使用できます。
import s
call_str = input("input which function you want to call:")
"""
if call_str == 'func1':
print(s.func1())
elif call_str == 'func2':
print(s.func2())
elif call_str == 'func3':
print(s.func3())
else:
print("404 NOT Found")
"""
if hasattr(s,call_str): #判断在s中是否存在函数call_str
obj = getattr(s,call_str)
print(obj())
else:
print("404 NOT Found")
クラスでReflectionが使用されています。
class Student:
#ROLE是一个属性
ROLE = 'User1'
@classmethod
def check_course(self):
print("查看课程")
@staticmethod
def login():
print("登录")
#查看属性
print(Student.ROLE)
#反射查看属性,‘ROLE’,引号引着是一个字符串,也就是用字符串‘ROLE‘
#去反射Student类中的属性ROLE
print(getattr(Student,'ROLE'))
#反射调用方法
getattr(Student,'check_course')()
#反射调用静态方法
getattr(Student,'login')()
反射はオブジェクトで使用されます。
class A:
def __init__(self,name):
self.name = name
def func(self):
print("in func")
#实例化对象,并给name赋值
a = A('rain')
#查看name属性
print(getattr(a,'name'))
#对象调用方法
getattr(a,'func')()
リフレクションはモジュールで使用されます:
import os
#rename('原名','要改成的名')
os.rename('__init__.py','init')
getattr(os,'rename')('init','__init__.py')