【问题标题】:Python's Abstract class doesn't return error on instantiation of incomplete concrete classPython的抽象类在实例化不完整的具体类时不返回错误
【发布时间】:2017-06-21 20:34:32
【问题描述】:

我是一名习惯于 C# 编程的程序员,我正在尝试使用 python 的抽象类来实现类似于 C# 接口的功能。

C#

如果我想确保某个类(以下示例中的 Concrete)具有某些属性或方法,我将创建一个接口 IBase,并确保该类实现该接口。如果类没有实现所有必需的方法和属性,编译器就会返回一个错误。

例子:

public interface IBase
    {
        void Foo();
        void Bar();
    }

    public class Concrete : IBase
    {
        public void Foo()
        {
            Console.WriteLine("Foo is implemented");
        }
    }

结果:

Program.cs(25,33): error CS0535: 'Program.Concrete' does not implement interface member 'Program.IBase.Bar()'

Python (2.7)

我试图在 python (2.7) 中实现类似的东西。通过使用抽象方法创建一个抽象类 Base 并使该类 Concrete 成为该抽象类的子类。应该发生的是,如果控制台没有获得所有必需的方法和属性,则在实例化对象时会抛出错误,但在以下示例中,程序似乎运行良好,直到实际调用缺少的函数。

例子:

from abc import ABCMeta, abstractmethod

class Base:
    _metaclass_ = ABCMeta

@abstractmethod
def Foo(self):
    raise NotImplementedError()

@abstractmethod
def Bar(self):
    raise NotImplementedError()

class Concrete(Base):
    def Foo(self):
        print "Foo is implemented"

c = Concrete()
c.Foo()
c.Bar()

结果:

Foo is implemented
Traceback (most recent call last):
  File "temp.py", line 27, in <module>
      c.Bar()
  File "temp.py", line 19, in Bar
      raise NotImplementedError()
NotImplementedError

如果有人能告诉我出了什么问题,我将不胜感激。

【问题讨论】:

  • '_metaclass_' != '__metaclass__'。此外,您的缩进似乎关闭了,您应该使用新型类。

标签: c# python abstract-class


【解决方案1】:

@johnsharpe 的评论是正确的:

class Base(object):
    __metaclass__ = ABCMeta
    @abstractmethod
    def Foo(self):
        raise NotImplementedError
    @abstractmethod
    def Bar(self):
        raise NotImplementedError

class Concrete(Base):
    def Foo(self):
        print 'Foo is implemented'



>>> c = Concrete()

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    c = Concrete()
TypeError: Can't instantiate abstract class Concrete with abstract methods Bar
>>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-27
    • 2011-03-20
    • 2013-05-13
    • 2014-01-11
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多