zoukankan      html  css  js  c++  java
  • 反射机制

    反射:通过字符串的形式去模块,对象中找寻指定的函数(方法)并执行。

    hasattr

    class Person(object):
        def talk(self):
            print('skr')
    
    p = Person()
    print(hasattr(p, 'talk'))
    print(hasattr(p, 'say_hello'))
    
    # True
    # False

    getattr

    class Person(object):
        def talk(self):
            print('skr')
    
    p = Person()
    func = getattr(p, 'talk')
    print(func)
    func()
    
    # <bound method Person.talk of <__main__.Person object at 0x0000000002A73358>>
    # skr

    setattr

    def say_hello(self):
        print('hello!')
    
    class Person(object):
        def talk(self):
            print('skr')
    
    p = Person()
    setattr(p, 'say_hello', say_hello)
    p.say_hello(p)
    # hello!

    delattr

    class Person(object):
        def talk(self):
            print('skr')
    
    p = Person()
    delattr(p, 'talk')
    p.talk()
    
    Traceback (most recent call last):
      File "oop.py", line 8, in <module>
        delattr(p, 'talk')
    AttributeError: 'Person' object attribute 'talk' is read-only

    p = Person()
    setattr(p, 'hehe', 111)
    p.hehe
    delattr(p, 'hehe')
    p.hehe

    Traceback (most recent call last):
      File "oop.py", line 12, in <module>
        p.hehe
    AttributeError: 'Person' object has no attribute 'hehe'
  • 相关阅读:
    108.将有序数组转换成二叉搜索树
    剑指Offer 09.用两个栈实现队列
    215.数组中的第K个最大元素
    AcWing 845.八数码
    1.两数之和
    迷宫问题
    倒计时
    Redis 红包
    Redis
    EF Api 全套
  • 原文地址:https://www.cnblogs.com/allenzhang-920/p/9503167.html
Copyright © 2011-2022 走看看