gpt4 book ai didi

python - Python中的抽象属性

转载 作者:IT老高 更新时间:2023-10-28 20:30:15 24 4
gpt4 key购买 nike

在 Python 中用抽象属性实现以下 Scala 代码的最短/最优雅的方法是什么?

abstract class Controller {

val path: String

}

Controller 的子类被 Scala 编译器强制定义“路径”。子类如下所示:

class MyController extends Controller {

override val path = "/home"

}

最佳答案

Python 3.3+

from abc import ABCMeta, abstractmethod


class A(metaclass=ABCMeta):
def __init__(self):
# ...
pass

@property
@abstractmethod
def a(self):
pass

@abstractmethod
def b(self):
pass


class B(A):
a = 1

def b(self):
pass

未能在派生类B中声明ab会引发TypeError如:

TypeError: Can't instantiate abstract class B with abstract methods a

Python 2.7

有一个 @abstractproperty装饰器:

from abc import ABCMeta, abstractmethod, abstractproperty


class A:
__metaclass__ = ABCMeta

def __init__(self):
# ...
pass

@abstractproperty
def a(self):
pass

@abstractmethod
def b(self):
pass


class B(A):
a = 1

def b(self):
pass

关于python - Python中的抽象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2736255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com