python hasattr() 区分方法和属性

Cod*_*755 5 python oop

正如一些好人向我展示的那样,callable()可以用来解决这个问题,我仍然发现这是一个不同的问题,因为任何想到这个问题的人都不会找到答案,因为他不会将其直接连接到callable(). 另外,我找到了一种不使用的可能方法,即按照我自己的一个答案中所示的方式callable()使用。type()

假设我创建一个简单的类Cls

class Cls():
    attr1 = 'attr1'

    def __init__(self, attr2):
        self.attr2 = attr2

    def meth1(self, num):
        return num**2

obj = Cls('attribute2')
print(hasattr(obj, 'attr1'))  # >>> True
print(hasattr(obj, 'attr2'))  # >>> True
print(hasattr(obj, 'meth1'))  # >>> True
Run Code Online (Sandbox Code Playgroud)

据我所知,属性是类内的变量,方法是类内的函数。他们不一样。

显然,Python 无法hasmethod()调用。看来这真的为我的测试提供hasattr()了一切,,。它与属性或方法没有区别。True'attr1''attr2''meth1'

如果我使用dir(),属性和方法将全部显示在输出中,并且您也无法真正分辨出哪一个是什么类型。

有人可以解释一下为什么吗?

Swe*_*per 5

无论是变量还是方法,它们都被视为“属性”。于是hasattr返回True

方法的不同之处在于它们是可调用的。这可以通过调用来检查callable。所以如果你想弄清楚一个属性是否可调用,你可以

if hasattr(obj, "attr1"):
    if callable(obj.attr1):
        # attr1 is a method!
    else:
         # attr1 is not a method but an attribute
else:
    # attr1 is not an attribute
Run Code Online (Sandbox Code Playgroud)