码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习之反射

时间:2020-02-20 14:51:36      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:input   val   attribute   字符   对象   elf   strip   self   cheng   

#!/usr/bin/env python
#-*-coding:utf8-*-

def bulk(self):
    print("%s is jiao ...."%self.name)

class Dog(object):
    def __init__(self,name):
        self.name=name


    def eat(self,food):
        print("%s is eating ...."%self.name,food)

d= Dog("dfxa")
choice = input(">>:").strip()

if hasattr(d,choice):  #判断一个d(对象)里是否有对应的choice字符串方法
# delattr(d,choice) # Deletes the named attribute from the given object. # delattr(x, ‘y‘) is equivalent to ``del x.y‘‘ # 相当于 del d.choice
func = getattr(d,choice) #根据字符串去获取d对象里的对应方法的内存地址 func("cheng") # attr = getattr(d,choice) # setattr(d,choice,"drr") else: # 将给定对象的命名属性设置为指定值 setattr(d,choice,22) # choice是字符串,相当于 d.choice = z print(getattr(d,choice)) print(d.name)
  setattr(d,choice,bulk)
  d.tlk(d)  #动态的把类外面的方法装配到类里,通过字符串的形式,调用需要把自己传进去
输入 tlk才能调用
>>:tlk

dfxa is jiao ....

 

Python学习之反射

标签:input   val   attribute   字符   对象   elf   strip   self   cheng   

原文地址:https://www.cnblogs.com/wengshaohang/p/12335636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!