Python類的反射實例
打開python開發(fā)工具IDLE在編寫Python代碼之前,我們首先需要打開一個Python開發(fā)工具。IDLE是Python自帶的一個簡單的集成開發(fā)環(huán)境(IDE),可以方便地編寫和運行Python代碼
打開python開發(fā)工具IDLE
在編寫Python代碼之前,我們首先需要打開一個Python開發(fā)工具。IDLE是Python自帶的一個簡單的集成開發(fā)環(huán)境(IDE),可以方便地編寫和運行Python代碼。在IDLE中新建一個名為""的文件,并將以下代碼復(fù)制到文件中:
```python
class Test():
def __init__(self, name):
self._name name
def test1(self):
print('test1')
t1 Test('hello')
print(globals())
```
利用globals()函數(shù)實現(xiàn)反射
在上述代碼中,我們定義了一個Test類,并創(chuàng)建了一個t1對象。接下來,我們可以使用`globals()`函數(shù)來實現(xiàn)反射。通過`globals()`函數(shù),我們可以獲取全局變量的字典,其中包含我們定義的Test類和t1對象。
```python
clz 'Test'
fn 'test1'
t2 globals()[clz]('world')
fun getattr(t2, fn)
fun()
```
通過類名的key,我們可以定位到類的地址,然后實例化一個t2對象。再利用`getattr()`函數(shù),我們可以獲取對象的方法并調(diào)用。
直接使用getattr方法
除了上述步驟,我們還可以直接在創(chuàng)建對象后使用`getattr()`方法來調(diào)用對象的方法。
```python
class Test():
def __init__(self, name):
self._name name
def test1(self):
print('test1')
t1 Test('hello')
f1 getattr(t1, 'test1')
f1()
clz 'Test'
fn 'test1'
t2 globals()[clz]('world')
fun getattr(t2, fn)
fun()
```
通過上述代碼,我們可以看到對象t1也可以調(diào)用test1()方法。
判斷函數(shù)是否存在
在使用反射時,有時我們需要判斷一個類是否擁有某個方法??梢允褂胉hasattr()`方法來判斷函數(shù)是否存在。
```python
class Test():
def __init__(self, name):
self._name name
def test1(self):
print('test1')
t1 Test('hello')
print(hasattr(t1, 'test1'))
f1 getattr(t1, 'test1')
f1()
clz 'Test'
fn 'test1'
t2 globals()[clz]('world')
fun getattr(t2, fn)
fun()
```
通過以上代碼,我們可以看到輸出結(jié)果為True,表示類Test存在test1()方法。