本文介绍了`staticmethod` 和 `abc.abstractmethod`:它会融合吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Python 应用程序中,我想创建一个既是 staticmethod 又是 abc.abstractmethod.我该怎么做?

In my Python app I want to make a method that is both a staticmethod and an abc.abstractmethod. How do I do this?

我尝试应用两个装饰器,但它不起作用.如果我这样做:

I tried applying both decorators, but it doesn't work. If I do this:

import abc

class C(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    @staticmethod
    def my_function(): pass

我得到一个例外*,如果我这样做:

I get an exception*, and if I do this:

class C(object):
    __metaclass__ = abc.ABCMeta

    @staticmethod
    @abc.abstractmethod
    def my_function(): pass

不强制执行抽象方法.

如何创建一个抽象的静态方法?

How can I make an abstract static method?

*例外:

File "c:Python26Libabc.py", line 29, in abstractmethod
 funcobj.__isabstractmethod__ = True
AttributeError: 'staticmethod' object has no attribute '__isabstractmethod__'

推荐答案

class abstractstatic(staticmethod):
    __slots__ = ()
    def __init__(self, function):
        super(abstractstatic, self).__init__(function)
        function.__isabstractmethod__ = True
    __isabstractmethod__ = True

class A(object):
    __metaclass__ = abc.ABCMeta
    @abstractstatic
    def test():
        print 5

这篇关于`staticmethod` 和 `abc.abstractmethod`:它会融合吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 05:36