除非实现方法,否则我可以阻止类定义吗? [英] Can I prevent class definition unless a method is implemented?

查看:75
本文介绍了除非实现方法,否则我可以阻止类定义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何为插件编写者提供基类,以便他们为几种静态方法提供定义。

I'm trying to figure out how to provide a base class to plugin writers so that they provide definitions for several static methods.

插件类是一个集合永远不会被实例化的静态方法。

A plugin class is a collection of static methods which will never be instantiated.

我知道如何使用ABC来防止类的 instantiation 丢失方法的实现,这不会提供我想要的安全性。有没有防止定义的模式?

I know how to use ABC to prevent instantiation of a class missing method implementations, which will not provide the safety I would like. Is there a pattern to prevent definition?

推荐答案

您可以通过编写类似自己的元类来实现交给ABCMeta,后者会在类定义时检查抽象方法,如果发现抽象方法,则会引发错误。下面是一个示例:

You can do it by writing your own metaclass similar to ABCMeta, which checks for abstract methods at class-definition time and raises an error if it finds any. Here's an example:

class ClassABC(type):
    def __init__(cls, name, bases, attrs):
        abstracts = set()
        for base in bases:
            abstracts.update(getattr(base, '__abstractclassmethods__', set()))
        for abstract in abstracts:
            if getattr(getattr(cls, abstract), '__isabstractmethod__', False):
                raise TypeError("Your class doesn't define {0}".format(abstract))
        for attr in attrs:
            if getattr(attrs[attr], '__isabstractmethod__', False):
                abstracts.add(attr)
        cls.__abstractclassmethods__ = abstracts

class BaseClass(object):
    __metaclass__ = ClassABC

    @abc.abstractmethod
    def foo(self):
        print("I am base foo")

然后:

>>> class Derived(BaseClass):
...     pass
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    class Derived(BaseClass):
  File "<pyshell#8>", line 8, in __init__
    raise TypeError("Your class doesn't define {0}".format(abstract))
TypeError: Your class doesn't define foo

我的示例相当快捷又脏又脏,只经过了严格的测试,您可能需要对其进行改进以检查各种边缘情况。我要做的是,如果当前正在定义的类中没有定义一个抽象方法,则会引发错误。 (否则将引发错误,因为抽象基类未定义其自己的抽象方法的具体实现。)

My example is fairly quick and dirty and only scantily tested, and you might want to refine it to check various sorts of edge cases. What I did is I raised the error if there is an abstract method that wasn't defined in the currently-being-defined class. (Otherwise an error would be raised because the abstract base class doesn't define concrete implementations of its own abstract methods.)

这篇关于除非实现方法,否则我可以阻止类定义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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