python-普通类中的抽象方法 [英] python - abstract method in normal class

查看:251
本文介绍了python-普通类中的抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读正式的python 文档

I was reading official python documentation.

在上述链接中,第二行指出:

In the mentioned link, the second line states that:


使用此修饰符要求该类的元类是ABCMeta或从其派生的

Using this decorator requires that the class’s metaclass is ABCMeta or is derived from it.

但是,我能够成功定义以下给定的类

But, I was successfully able to define the below given class.

from abc import abstractmethod

class A(object):
    def __init__(self):
        self.a = 5
    @abstractmethod
    def f(self):
        return self.a

a = A()
a.f()

因此,上面的代码可以正常工作。
而且,我能够创建一个子类

So, the code above worked fine. And also, I was able to create a subclass

class B(A):
    def __init__(self):
        super(B, self).__init__() 

b = B()
b.f()

而不会覆盖上面定义的抽象方法。

Without overriding the abstract method defined above.

因此,基本上,这意味着如果我的基类是 metaclass 不是 ABCMeta (或从其派生),该类的行为不像抽象类,即使我有

So, basically does this mean that if my base class's metaclass is not ABCMeta(or derived from it), the class does not behave like an abstract class even though I have an abstract method in it?

这意味着文档需要更清晰吗?

That means, the documentation needs more clarity?

或者,这是行为吗?

推荐答案


所以,基本上,这意味着如果我的基类的元类不是
ABCMeta(或从它派生的),即使我有抽象方法,该类的行为也不像
抽象类吗?

So, basically does this mean that if my base class's metaclass is not ABCMeta(or derived from it), the class does not behave like an abstract class even though I have an abstract method in it?

正确。

全部抽象方法所做的用 __ isabstractmethod__ = True 标记该方法。 ABCMeta 完成所有实际工作。 此处抽象方法:

All abstractmethod does is mark the method with __isabstractmethod__ = True. ABCMeta does all the real work. Here is the code for abstractmethod:

def abstractmethod(funcobj):
    """A decorator indicating abstract methods.
    Requires that the metaclass is ABCMeta or derived from it.  A
    class that has a metaclass derived from ABCMeta cannot be
    instantiated unless all of its abstract methods are overridden.
    The abstract methods can be called using any of the normal
    'super' call mechanisms.
    Usage:
        class C(metaclass=ABCMeta):
            @abstractmethod
            def my_abstract_method(self, ...):
                ...
    """
        funcobj.__isabstractmethod__ = True
        return funcobj

这篇关于python-普通类中的抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆