ISINSTANCE和抽象基础类
我正在尝试检查对象是否具有方法开始
和方法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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过执行
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 methodsstart
andupdate
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