即使没有覆盖所有抽象方法,动态加载的子类仍然可以实例化

2024-10-02 20:42:27 发布

您现在位置:Python中文网/ 问答频道 /正文

设置:Python 3.3

我有一个名为SourceBase的基类,它定义了抽象方法和值:

import abc

class SourceBase(object):
    __metaclass__=abc.ABCMeta
    pluginid='undefined' #OVERRIDE THIS IN YOUR SUBCLASS. If you don't, the program will ignore your plugin.

    @abc.abstractmethod
    def get_images(self):
        '''This method should return a list of URLs.'''
        return

    @abc.abstractmethod
    def get_source_info(self):
        '''This method should return a list containing a human friendly name at index 0, and a human readable url describing the source for this repository.
        For example, the EarthPorn subreddit returns a list ['EarthPorn Subreddit', 'http://reddit.com/r/EarthPorn'].
        This is used to populate the treeview object with your source information.'''
        return

    @abc.abstractmethod
    def get_pluginid(self):
        '''This method should return a string that represents this plugins ID.
        The pluginid is used to make calls to this plugin when necessary. It should be unique as ids are in a shared pool,
        so make sure the id is unique. The id should remain the same even when updated as some settings with the pluginid 
        are persisted by the main application, and they will be lost if the id changes.
        '''
        return

这是我写的一些python插件的超类,它是这个的子类。它们是在运行时动态加载的,所有这些都可以工作,只是即使我在SourceBase中添加了一个新的抽象方法,插件仍然可以加载。他们不应该,因为他们都没有我的新方法。(我给了它@abc.抽象方法标记)。你知道吗

我的googlefu没有显示任何东西,所以我不知道为什么我仍然可以实例化这些插件,尽管超类说它们是抽象的。你知道吗

例如,在SourceBase中,我添加了:

@abc.abstractmethod
def get_dependencies(self):
    print('ERROR: THIS PLUGIN SHOULD NOT HAVE LOADED.')
    '''This method should return a list of package names. The host program will check if these packages are available.
    If they are not available, the plugin will be disabled, but the user will be able to elect to install these packages.'''
    return

我没有在我的插件中定义这个方法,但是我仍然在终端上得到这个输出:

....
Screen Height:1080
Screen Width:1920
files:  ['bingIOTD.py', 'redditEP.py', 'redditLP.py', '__init__.py']
ERROR: THIS PLUGIN SHOULD NOT HAVE LOADED. <--abstract method

我不知道为什么它忽略了它,我是不是遗漏了什么。。。?我以前用过不动态加载的普通类。感谢您的帮助。我知道我可能可以做一个变通方法(做一个默认的返回,检查它),但这似乎不是正确的方法。你知道吗

如果您需要更多的源代码,我的项目在SourceForgehere.


Tags: theto方法selfgetreturndefthis
1条回答
网友
1楼 · 发布于 2024-10-02 20:42:27

In Python3元类由

class SourceBase(metaclass=abc.ABCMeta):

不是

class SourceBase(object):
    __metaclass__=abc.ABCMeta

代码忽略了abstractmethod装饰器,因为就Python3而言,SourceBase只是一个带有属性名称__metaclass__的标准类(type的实例),而不是abc.ABCMeta的实例。你知道吗

相关问题 更多 >