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'
  • 相关阅读:
    swift基本数据类型的使用
    宏定义单例类
    开发必备宏定义大全
    GUI02
    GUI01
    浅谈代码块的加载顺序
    Java里的多态
    在java中this和super的使用
    冒泡排序的简单优化
    命令行传参和不定传参
  • 原文地址:https://www.cnblogs.com/allenzhang-920/p/9503167.html
Copyright © 2011-2022 走看看