zoukankan      html  css  js  c++  java
  • 反射

    反射是通过字符串的形式操作对象相关的成员

    # 反射
    class Fuck(object):
        def __init__(self):
            self.name = 'z'
            self.age = 22
        def run(self):
            return 'running'
    
    f = Fuck()
    # 查看有没有类成员,返回布尔值
    print(hasattr(f, 'name'))
    print(hasattr(f, 'age'))
    print(hasattr(f, 'run'))
    
    # 获取值,拿到一个返回值
    print(getattr(f, 'name'))
    print(getattr(f, 'age'))
    print(getattr(f, 'run'))
    
    # 设置值,有则修改,没有则创建,没有返回值
    setattr(f, 'name', 11)
    print(f.name)
    setattr(f,'gaga',21232)
    print(f.gaga)
    setattr(f,'run',111)
    print(f.run)

    # 删除一个已有的值,没有返回值
    delattr(f, 'name')
    print(f.name)

    #访问对象的属性有三种方法
    print(f.name)
    print(f.__dict__['name'])
    print(getattr(f,'name'))


    import sys
    class A(object):
    def __init__(self):
    self.name='z'
    self.age=11

    def run():
    print('hh')

    a=sys.modules[__name__]

    print(a)# 打印当前模块的名字
    print(hasattr(a,'run'))#查看当前模块下有没有run
    print(hasattr(a,'A'))#查看当前模块下有没有A
  • 相关阅读:
    final
    Leetcode Single Number
    Leetcode Implement strStr()
    Leetcode Count and Say
    Leetcode Paint Fence
    Leetcode Isomorphic Strings
    Leetcode Min Stack
    Leetcode Valid Sudoku
    Leetcode Two Sum III
    Leetcode Read N Characters Given Read4
  • 原文地址:https://www.cnblogs.com/z-x-y/p/9077630.html
Copyright © 2011-2022 走看看