Python 入門 之 反射

2021-10-01 18:29:40 字數 2405 閱讀 3306

​ 反射主要是指程式可以訪問、檢測和修改它本身狀態或行為的一種能力(自省)。

<1> getattr() 獲取

<2> setattr() 設定

<3> hasattr() 判斷是否存在

<4> delattr() 刪除

class a:

def __init__(self,name):

self.name = name

def func(self):

print("is a func")

a = a("rimo")

a.func()

print(a.name)

a.func()

領域:web開發,爬蟲,資料分析,資料探勘,人工智慧

零基礎到專案實戰,7天學習上手做專案

class a:

def __init__(self,name):

self.name = name

def func(self):

print("is a func")

a = a("rimo")

print(hasattr(a,"name")) # 返回 true就是說明name這個屬性在物件a中存在

print(getattr(a,"name"))

f = getattr(a,"func")

f()setattr(a,"age",18)

print(a.__dict__)

delattr(a,"name")

print(a.__dict__)

class a:

def __init__(self,name):

self.name = name

def func(self):

print("is a func")

a = a("rimo")

print(hasattr(a,"name"))

f = getattr(a,"func")

f(11)

def func():

print("is func")

# 當前模組:

print(globals()["func"])

import sys

o = sys.modules[__name__] # 獲取當前模組名對應的物件

f = getattr(o,"func")

f()

import test       # 匯入模組

test.func()

o = globals()["test"]

getattr(o,"func")()

class blog:

def login(self):

print("is login")

def register(self):

print("is register")

def comment(self):

print("is comment")

def log(self):

print("is log")

def log_out(self):

print("is log_out")

b = blog()

func_dic =

msg = """

1.登入

2.註冊

4.日誌

5.登出

"""choose = input(msg)

if choose in func_dic:

func_dic[choose]()

將上述**進行修改,減少**(通過字串操作物件的屬性和方法)
class blog:

def login(self):

print("is login")

def register(self):

print("is register")

def comment(self):

print("is comment")

def log(self):

print("is log")

def log_out(self):

print("is log_out")

b = blog()

msg = """

login

register

comment

loglog_out

"""while 1:

choose = input(msg)

if hasattr(b,choose):

getattr(b,choose)()

else:

print("請重新輸入!")

Python之反射練習

什麼是反射?可以用字串的方式去訪問物件的屬性 class test name sss deffun self return helloword t test print hasattr t,name hasattr obj,name 檢視類裡面有沒有name屬性 print hasattr t,fu...

python之反射機制

匯入模組方式 單層匯入 import os import os 多層匯入 from util.excel import excel import util.excel.excel fromlist true 如果不加上fromlist true,只會匯入list目錄 反射方式 反射即想到4個內建函式...

python之反射 選課例子

在這個例子中用到了反射和列舉的用法,裡面有各種注意事項,是個不錯的練習題 total couese list 把函式run中的變數當成全域性變數放在這裡 class course def init self,name,price,period self.name name self.price pr...