zoukankan      html  css  js  c++  java
  • 030反射

    ###反射
    ## getattr,hasattr,setattr,delattr,和类里面的字段有关,具体看例子

    #1
    class  Person:
        def  __init__(self,name,age):
            self.name = name
            self.age = age
        def  show_lover(self):
            print('lover')
        
    o = Person('x',21)
    b = 'name'
    print(o.__dict__[b])
    
    # 2 
    b = input('>>>')
    if  hasattr(o,b):
        v = getattr(o,b)        # 去什么东西里面获取什么内容   
        delattr(o,b)
        setattr(o,'age',21)
    print(v)
    func=getattr(o,'show_lover')   # 拿到方法
    func()
    View Code

    # 3 拿到类对象的字段

    class  Person:
        stat = '123'
        def  __init__(self,name,age):
            self.name = name
            self.age = age
    
    r = getattr(Person,'stat')
    print(r)

    # 4拿到其他模块的函数和字段等

    # s.py
    NAME = '_nbloser'
    def  func():
        return'func'
    class  Person:
        def  __init__(self):
    
    self.name = '_nbloser'
    # 执行.py
    import s
    r1 = getattr(s,'NAME')
    r2 = getattr(s,'func')
    Pers = getattr(s,'Person')
    p1 = Pers()
    print(r1,r2(),p1.name)      # _nbloser   func   _nbloser

    # 应用小例子

    def  f1():
        return'首页'
    def  f2():
        return'新闻'
    def  f3():
        return'精华'
    
    import  s
    inp = input('>>')
    if  hasattr(s,inp):
        func = getattr(s,inp)
        print(func())
    else:
        print(404)
  • 相关阅读:
    Wannafly 挑战赛12 E
    HIT ACM 2018春 week2 codeforces.com/gym/101652 题解
    Hihocoder [Offer收割]编程练习赛49 题目4 : 第K小先序遍历
    HDU
    ZOJ
    HYSBZ
    POJ
    HYSBZ
    POJ 2796 Feel Good 题解
    逆元基本知识
  • 原文地址:https://www.cnblogs.com/-nbloser/p/8337874.html
Copyright © 2011-2022 走看看