面向对象---反射

#反射是由Smith在1982年提出,主要是指程序可以访问、检测和修改它本身状态或行为的一种能力(自省)

#python面向对象种的反射:通过字符串的形式操作对象相关的属性。

#四个可以实现自省的函数 下列方法适用于类和对象(一切皆对象,类本身也是一个对象)

hasattr(object,name)

#判断object中有没有一个name字符串对应的方法或属性 返回True or None

getattr(object,name,default=None)

#拿到object中的name属性,如果没有 返回default的默认值None(实际应用中直接第三个参数写None,不用带上default=),没有默认参数
#则报错

setattr(object,‘sex’,‘male’)#本质就是object.sex=‘male’

#修改,object是对象,sex是想要修改的对象,male是修改对象的内容。也可以添加某个属性

delattr(object,name) # 本质就是del object.name

delattr(x, ‘y’) is equivalentto``del x.y’’

#删除操作

class Food:
    feature='Can eat'
    def __init__(self,kind,kind1,kind2):
        self.kind=kind
        self.kind1=kind1
        self.kind2=kind2

    def enough(self):
        print('Enough to eat')

    def insufficient(self):
        print('Not enough to eat')

hap=Food('烧鸡','烤鸭','西瓜')


print(hasattr(hap,'kind1'))   #判断hap 中有没有kind1对应的属性或者方法,返回布尔值

print(getattr(hap,'kind'))  #拿到 hap 中 kind 的属性
func=getattr(hap,'enough')
func()                     #拿到hao中 enough 对应的功能,返回的是个函数名,然后加括号来调用函数

setattr(hap,'kind3','啤酒')
print(hap.__dict__)           # 添加
setattr(hap,'kind2','凉菜')
print(hap.__dict__)           # 修改

delattr(hap,'kind2')
print(hap.__dict__)         # 删除

class Service:
    def run(self):
        while 1 :
            inp=input('>>')
            if hasattr(self,inp):
                func=getattr(self,inp)
                func()
    def get(self):
        print('get.....')

    def open(self):
        print('open....')

p=Service()
p.run()

运行结果:

>>get
>>get....
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值