【问题标题】:How to implement abstract class methods as static method in inherited class in python?如何在python的继承类中将抽象类方法实现为静态方法?
【发布时间】:2015-10-12 06:38:22
【问题描述】:

我正在开发 python 2.7。 我需要实现一个具有抽象方法的类。这个类的所有方法都应该实现为静态方法。

例子:-

from abc import ABCMeta, abstractmethod


class HelperABC(object):

    __metaclass__ = ABCMeta

    @abstractmethod
    def method_name(my_message):
        pass

在上面的类中,我需要使用 method_name(my_message) 并将其实现为静态方法。

我想把它用作:-

@staticmethod
def method_name(my_message):
   "code"

请告诉我如何实现它。

我尝试将装饰器 @staticmethod 和 @abstractmethod 都放在下面:-

@abstractmethod
@staticmethod
def method_name(my_message):
    pass

这也不起作用。

【问题讨论】:

  • 第一次尝试有什么问题 - 仅限 @staticmethod
  • @AnandSKumar 当我只使用@staticmethod 时,它在实现的类中显示如下内容:- @staticmethod def method_name(my_message): HelperABC.debug(my_message) 在实现的类中,它正在创建一个抽象类的对象。所以,我认为这不是在 python 中使用抽象类的正确方法。

标签: python inheritance


【解决方案1】:

如下修改您的方法。我试过了,它对我有用:

@staticmethod
@abstractmethod
def method_name(my_message):
    pass

【讨论】:

  • python 3.3 中引入的属性聚合
猜你喜欢
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 2014-11-30
  • 1970-01-01
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 2014-02-17
相关资源
最近更新 更多