python笔记 hasattr

160 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第22天,点击查看活动详情

0 环境

  • 编辑器:pycharm或者vscode
  • 系统版本:windows10
  • python版本:3.9.6

1 hasattr

之前我们使用getattr和setattr知道了,getattr可以获得属性和方法,不存在的话,会报错,setattr当不存在时,动态添加,那么针对getattr获取的属性或者方法不存在的情况该怎么避免呢,如下图:

image.png

image.png

有么有现成的解决方案呢,hasattr体现它存在的意义就存在了,用来判断属性或者方法是否存在的。存在就是真,不存在就是假。如下代码:

class Demo:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def show(self):
        print("show")

d = Demo(1, 2)
print("属性 -->", hasattr(d, "a"))
print("属性 -->", hasattr(d, "b"))
print("属性 -->", hasattr(d, "show"))
print("属性 -->", hasattr(d, "show1"))

image.png

这样就不用添加异常处理了,直接先if判断该属性或方法,是否存在,存在进入执行。

那么我们就回顾下所学的两个attr,获取、判断整合在一起(setattr自行扩展),如下代码:

我在Demo1的类中定义了三个show开头某某方法,并且打印对应方法名,重点在于这里的go方法里执行的,现在是一个无限while循环,除非我输入exit或quit才会退出,当我在输入框中输入内容,判断这个方法是否存在,存在直接打印结果记住getattr()后需要跟着(),方法才会执行。然后如果不存在,打印结果不存在。但是这里hasattr的判断,可以直接使用getattr(self, console, lambda : print(f"方法为{console},未找到!!!"))()就可以代替。

class Demo1:

    def show(self):
        print("show")

    def show1(self):
        print("show1")

    def show2(self):
        print("show2")

    def go(self):
        while True:
            console = input("--->").strip()
            if console == "quit" or console == "exit":
                return
            
            # getattr(self, console, lambda : print(f"方法为{console},未找到!!!"))() 等同于如下代码s
            if hasattr(self, console):
               getattr(self, console)()sh

            else: 
               print(f"方法为{console},未找到!!!")
               
d1 = Demo1()
d1.go()

image.png

2 总结

了解hasattr出现的好处,getattr得到不存在属性或方法会报错,也可以使用getattr第三个参数的用法来解决这个问题。对了,不要去纠结哪个更好,根据使用场景来,或者说根据个人喜好吧。