zoukankan      html  css  js  c++  java
  • 反射

    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': '骨头'}
    '''
  • 相关阅读:
    [Codeforces 1178D]Prime Graph (思维+数学)
    [Codeforces 316E3]Summer Homework(线段树+斐波那契数列)
    [Codeforces 997C]Sky Full of Stars(排列组合+容斥原理)
    [HDU 3625]Examining the Rooms (第一类斯特林数)
    [Codeforces 364D]Ghd(随机算法+gcd)
    【快速幂】POJ3641
    【二分查找】POJ2456-Aggressive cows
    【判断解是否可行-二分】POJ1064-Cable master
    【动态规划/递推】BZOJ1806[IOI2007]- Miners
    【动态规划去除冗余】NOIP2010-乌龟棋
  • 原文地址:https://www.cnblogs.com/cky-2907183182/p/11370383.html
Copyright © 2011-2022 走看看