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

    反射
    hasattr(obj,name_str),判断一个对象里是否有对应的字符串的方法
    getattr(obj,name_str),得到对象里对应字符串的方法,并执行

     1 class Dog(object):
     2     def __init__(self, name):
     3         self.name = name
     4 
     5     def eat(self, food):
     6         print('%s is eating ... %s' % (self.name, food))
     7         
     8 def bluk(self):
     9     print('%s is yell....' % self.name)
    10 
    11 
    12 d = Dog('dog1')
    13 
    14 choice = input('>>:')
    15 if hasattr(d, choice):
    16 
    17     # 删除属性
    18     delattr(d, choice)
    19     print(d.name)
    20 
    21     # 当输入name时,将name复制为dog
    22     # attr = getattr(d, choice)
    23     # setattr(d, choice, 'dog2')
    24     # print(d.name)
    25 
    26     # 当输入eat时的代码
    27     # getattr(d, choice)('meat')
    28 
    29 else:
    30 
    31     # 无方法,给属性直接赋值
    32     setattr(d, choice, 22)
    33     print(getattr(d, choice))
    34 
    35     # setattr(d,choice,None)
    36     # print(getattr(d,choice))
    37 
    38     # setattr(d, choice, bluk)
    39     # d.talk(d)
    View Code
  • 相关阅读:
    简单的多重背包
    完美子图
    活动投票
    人品问题
    售票系统
    最短路径
    优美值
    前端-常用函数记录-持续更新
    前端-单点登录中cookie中domain的思考
    大白话说GIT常用操作,常用指令git操作大全
  • 原文地址:https://www.cnblogs.com/Linc2010/p/9011621.html
Copyright © 2011-2022 走看看