物件導向之反射

2021-07-13 11:03:30 字數 1267 閱讀 8813

反射

python中的反射功能是由以下四個內建函式提供:hasattr、getattr、setattr、delattr,改四個函式分別用於對物件內部執行:檢查是否含有某成員、獲取成員、設定成員、刪除成員。

class foo(object):

def __init__(self):

self.name = 'wupeiqi'

def func(self):

return 'func'

obj = foo()

# #### 檢查是否含有成員 ####

hasattr(obj, 'name')

hasattr(obj, 'func')

# #### 獲取成員 ####

getattr(obj, 'name')

getattr(obj, 'func')

# #### 設定成員 ####

setattr(obj, 'age', 18)

setattr(obj, 'show', lambda num: num + 1)

# #### 刪除成員 ####

delattr(obj, 'name')

delattr(obj, 'func')

案例1:

class foo(object):

def __init__(self):

self.name = 'alex'

def func(self):

return 'func'

# 不允許使用 obj.name

obj = foo()

print getattr(obj, 'name')

案例2:類也是物件

class foo(object):

staticfield = "old boy"

def __init__(self):

self.name = 'wupeiqi'

def func(self):

return 'func'

@staticmethod

def bar():

return 'bar'

print getattr(foo, 'staticfield')

print getattr(foo, 'func')

print getattr(foo, 'bar')

物件導向之反射

isinstance與issubclass是python的內建模組 isinstance class foo pass class boo pass foo obj foo boo obj boo print isinstance foo obj,foo true print isinstance ...

物件導向之反射運用

import sysclass apache object def init self,tcp self.tcp tcp defstart self print apache is starting,host id is s self.tcp defstop self print apache is...

物件導向 反射

內建函式 1.isinstance 判斷乙個物件和乙個類有沒有血緣關係class a pass class b a pass a b print isinstance a,b true print isinstance a,a true print type a is b true print ty...