ISINSTANCE和抽象基础类

发布于 2025-01-24 02:22:00 字数 665 浏览 2 评论 0原文

我正在尝试检查对象是否具有方法开始和方法Update。 我认为我可以使用抽象基类,就像collections.abc.iterable工作一样。

就我而言,我不能做class foo(interface),因为foo是动态加载的,并且无法访问接口

检查对象是否具有特定方法的惯用方法是什么?

import abc


class Interface(abc.ABC):

    @abc.abstractmethod
    def start():
        pass

    @abc.abstractmethod
    def update():
        pass


class Foo:
    def start():
        pass

    def update():
        pass


def main():
    foo = Foo()
    print(f'{isinstance(foo, Interface) = }')  # False


if __name__ == '__main__':
    main()

I'm trying to check if an object has a method start and a method update.
I thought I could use abstract base class, just like collections.abc.Iterable work.

In my case I cannot do class Foo(Interface) since Foo is load dynamically, and have no access to Interface.

What is the idiomatic way to check if an object have specific methods ?

import abc


class Interface(abc.ABC):

    @abc.abstractmethod
    def start():
        pass

    @abc.abstractmethod
    def update():
        pass


class Foo:
    def start():
        pass

    def update():
        pass


def main():
    foo = Foo()
    print(f'{isinstance(foo, Interface) = }')  # False


if __name__ == '__main__':
    main()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

金橙橙 2025-01-31 02:22:00

您可以通过执行dir(foo)来获取类或类实例的所有方法。这将返回此类或实例可用的所有方法的列表。然后,您可以通过在dir(foo)中执行“ start”和dir(foo)<的“ start”来检查方法更新在此列表中。 /code>

注意,dir还将向您显示所有类变量和属性,因此您可能不想使用它。

您可以阅读有关此主题的更多信息在这里

You can get all the methods of a class or class instance by doing dir(foo). This will return you a list of all methods available for this class or instance. You can then check if methods start and update are inside this list by doing "start" in dir(foo) and "update" in dir(foo)

Note, that dir will also show you all of the class variables and properties, so you might not want to use it.

You can read more about this topic here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文