微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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

解决方法

如果我是我,我将开始使用类型检查器,例如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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。