为什么使用`@ abstractmethod`装饰的方法** **具有`__isabstractmethod__`属性为True?

时间:2018-04-26 02:29:28

标签: python python-3.x decorator python-decorators descriptor

考虑以下课程

from abc import abstractmethod

class K:

    @staticmethod
    def sm(*args):
        pass

    @classmethod
    def cm(*args):
        pass

    @abstractmethod
    def am(*args):
        pass

    # instance method
    def im(*args):
        pass

为什么未使用@abstractmethod修饰的方法的__isabstractmethod__属性设置为True

要重现此操作,您可以运行以下代码:

#  DON'T LET DESCRIPTORS' `__get__` methods be called!
#  USE THE DICT!
K_dct = object.__getattribute__(K, '__dict__')

sm = K_dct['sm']
cm = K_dct['cm']
am = K_dct['am']
im = K_dct['im']

ms = [sm, cm, am, im]

def go_soul_searching(obj):
    """
    :param obj:
    :return: string containing all global labels pointing to `obj`
    """
    g = globals()
    ns = [n for n in g.keys() if g[n] is obj]
    return '{' + ', '.join(ns[0:-1]) + ', ' + ns[-1] + '}'

print_nicely = lambda m, attrname: ''.join([str(x).ljust(25) for x in [
    attrname,
    str(hasattr(m, attrname))
]])

def inspect_method(m):
    header = '\n' + go_soul_searching(m) + '\n'
    print(header, end='')
    for attrname in inspect_method.attrs:
        print(print_nicely(m, attrname))
inspect_method.attrs = ['__call__', '__get__', '__set__', '__isabstractmethod__']

for m in ms:
    inspect_method(m)

输出为:

{sm, m} # STATIC METHOD
__call__                 False                    
__get__                  True                     
__set__                  False                    
__isabstractmethod__     True                     

{cm, m} # CLASS METHOD
__call__                 False                    
__get__                  True                     
__set__                  False                    
__isabstractmethod__     True                     

{am, m} # ABSTRACT METHOD
__call__                 True                     
__get__                  True                     
__set__                  False                    
__isabstractmethod__     True                     

{im, m} # INSTANCE METHOD
__call__                 True                     
__get__                  True                     
__set__                  False                    
__isabstractmethod__     False

1 个答案:

答案 0 :(得分:3)

很简单,您打印了(function ($) { $(document).ready(function(){ if ($("#wpadminbar").length) { $("#sticker-sticky").sticky({topSpacing:28}); }else { $("#sticker-sticky").sticky({topSpacing:0}); } }); })(jQuery); 的结果。是的,他们有属性。您没有检查属性的值。

hasattr