反射

1.hasattr

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

    def eat(self):
        print('%s吃饭' % self.name)

class Dog(Animal):
    pass

dog = Dog('小花狗')
print(hasattr(dog, 'eat'))
print(hasattr(dog, 'eater'))
print(hasattr(dog, 'name'))

out:
True
False
True

 

2.getattr

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

    def eat(self):
        print('%s吃饭' % self.name)

class Dog(Animal):
    pass

dog = Dog('小花狗')

print(getattr(dog, 'name'))
print(getattr(dog, 'eat'))
func = getattr(dog, 'eat')
func()
# 不指定default会报错
print(getattr(dog, 'food', '不存在的属性'))
out:
小花狗
<bound method Animal.eat of <__main__.Dog object at 0x00000217FD770AC8>>
小花狗吃饭
不存在的属性

 

当要反射自己模块中的变量(或函数,可以借助sys模块和__name__实现。使用变量__name__是因为在自己模块运行时,__name__就是__main__,

而如果该模块是被到入模块时,确保反射的还是此模块的变量(或函数)。

import sys

year = 2019
args = input('>>>')
print(getattr(sys.modules[__name__],args))

 

 

3.setattr(x,y,v)

def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.
    
    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass

 

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

    def eat(self):
        print('%s吃饭' % self.name)

class Dog(Animal):
    pass

dog = Dog('小花狗')

setattr(dog, 'food', '骨头')
setattr(dog, 'name', '王二狗')

print(dog.__dict__)
'''
打印结果
{'name': '王二狗', 'food': '骨头'}
'''

 

4.delattr

def delattr(x, y): # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.
    
    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass
class Animal:
    def __init__(self, name):
        self.name = name

    def eat(self):
        print('%s吃饭' % self.name)

class Dog(Animal):
    pass

dog = Dog('小花狗')

setattr(dog, 'age', 2)
setattr(dog, 'food', '骨头')
print(dog.__dict__)
delattr(dog, 'name')

print(dog.__dict__)
'''
打印结果
{'name': '小花狗', 'age': 2, 'food': '骨头'}
{'age': 2, 'food': '骨头'}
'''

 

posted @ 2019-08-17 21:15  tianqibucuo  阅读(117)  评论(0编辑  收藏  举报