python(反射hasattr、getattr、setattr、delattr)

# Author:Sooele
def bulk(self):
    print("%s cooioobbbbb..."%self.name)
class Dog(object):

    def __init__(self,name):
        self.name = name

    def eat(self,food):
        print("%s is eating ......."%self.name,food)


d = Dog("Cooi")
choice = input("》》》:").strip()

if hasattr(d,choice0):
    delattr(d,choice)           #delattr        #



if hasattr(d,choice):   #     hasattr(obj,name_str)
    # func = getattr(d,choice)       #getattr(obj,name_str)
    # func("Sooele")
    attr = getattr(d,choice)
    setattr(d,choice,"Sooeleoooooooo")        #setattr
else:
    # setattr(d,choice,22)
    # d.talk(d)
    setattr(d,choice,22)
    print(getattr(d,choice))
print(d.name)
#print(getattr(d,choice))       #内存对象地址

# 反射
#     hasattr(obj,name_str) ,判断一个对象obj里是否有对应的name_str字符串的方法
#     getattr(obj,name_str)  ,根据字符串去获取obj对象里的对应的方法的内存地址
#     setattr(obj,'y',z), is equivalen to  x.y=v
#     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')

发表评论