Python学习之反射
#!/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才能调用>>:tlkdfxa is jiao ....
相关推荐
pythonxuexi 2020-07-19
ciqingloveless 2020-06-19
guangmingsky 2020-06-01
bizercsdn 2020-05-10
小方哥哥 2020-05-10
flowerCSDN 2020-04-21
晓杰0 2020-04-20
txlCandy 2020-04-20
猛禽的编程艺术 2020-02-02
laityc 2020-01-01
jacktangj 2020-01-07
zhglinux 2019-12-25
jacktangj 2019-12-15
pythonxuexi 2019-11-30
heideyanmou 2019-03-21
sharkandshark 2012-03-20
orlandowww 2019-06-26
Lenskit 2019-06-27