python在类中实现swith case功能

问题

Python中没有switch的语法,但是很多时候需要多重条件判断,又不想写多个if,那只能手动实现了。 实现代码

class RunMethod:
    def post(self,url=None,data=None,header=None):
        print(url)
    def get(self,url=None,data=None,header=None):
        print("get")

    def main(self,method):
        method = getattr(self, method)
        return method

if __name__ == '__main__':
    client = RunMethod()
    client.main("post")("http://www.baidu.com")

其中主要用到getattr这个函数,用于返回一个对象属性值。

getattr(object, name[, default])
  • object -- 对象。
  • name -- 字符串,对象属性。
  • default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。

欢迎扫描下方二维码,持续关注:

互联网工程师(id:phpstcn),我们一起学习,一起进步

转载于:https://my.oschina.net/xushuhui/blog/3023171

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值