Python - 将父级或接口指定为 return 类型
Python - Specify parent or interface as return type
我是 Python 的新手,正在尝试了解如何在 python 中像在 Java 中一样实现如下内容。
public interface IParent {
}
public Class Parent1 implements IParent{
}
public Class Parent2 implements IParent{
}
Now, I can use like:
IParent p1 = new Parent1();
IParent p2 = new Parent2();
因此,试图了解我们如何在 Python 中实现这一目标。看到一些带有 TypeVar("T") 的 SO 文章,但无法理解。或者我们如何知道任何 class.
的 return 类型是什么
感谢这里的任何光线。
在Python中没有接口这样的东西。而是使用继承和so-called抽象基类(ABC),简单来说就是类无法实例化。您的代码将转换为:
from abc import ABC
class IParent(ABC):
pass
class Parent1(IParent):
pass
class Parent2(IParent):
pass
p1 = Parent1()
p2 = Parent2()
更详细的解释请参考this article
我是 Python 的新手,正在尝试了解如何在 python 中像在 Java 中一样实现如下内容。
public interface IParent {
}
public Class Parent1 implements IParent{
}
public Class Parent2 implements IParent{
}
Now, I can use like:
IParent p1 = new Parent1();
IParent p2 = new Parent2();
因此,试图了解我们如何在 Python 中实现这一目标。看到一些带有 TypeVar("T") 的 SO 文章,但无法理解。或者我们如何知道任何 class.
的 return 类型是什么感谢这里的任何光线。
在Python中没有接口这样的东西。而是使用继承和so-called抽象基类(ABC),简单来说就是类无法实例化。您的代码将转换为:
from abc import ABC
class IParent(ABC):
pass
class Parent1(IParent):
pass
class Parent2(IParent):
pass
p1 = Parent1()
p2 = Parent2()
更详细的解释请参考this article