Python区分抽象方法和抽象属性

2024-10-03 13:28:46 发布

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

在python中,有没有一种方法可以用抽象类强制使用属性vs方法

例如,如果我想强制执行如下方法:

Class AbstractCar(ABC):
  
  @abstractmethod
  def drive():
    pass

那么这个类仍然可以实例化

Class Car(AbstractCar):
  drive = 5 # This satisfies the @abstractmethod above but is not a method

反之亦然:

  @property
  @abstractmethod


Tags: 实例方法属性def抽象类passdrivethis
1条回答
网友
1楼 · 发布于 2024-10-03 13:28:46

如果我是你,我会开始使用类型检查器,比如mypy

最近每当我编写Python时,我总是尽量使用诸如flake8和mypy之类的工具进行验证,以确保它尽可能安全。以下是添加了一些类型提示的代码:

test.py

from abc import ABC, abstractmethod


class AbstractCar(ABC):
    @abstractmethod
    def drive(self) -> None:
        pass


class Car(AbstractCar):
    drive = 5

下面是执行这种超控的警告:

$ mypy test.py
mypy.py:10: error: Incompatible types in assignment (expression has type "int",
base class "AbstractCar" defined the type as "Callable[[AbstractCar], None]")
Found 1 error in 1 file (checked 1 source file)

相关问题 更多 >