Python中的实体

2024-04-20 12:05:52 发布

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

对不起,如果我的问题错了,但我想知道。在

class MyCustomException(KeyError):
  def __init__(self, *args):
    super().__init__(*args)


def method(d):
  return d['name']

try:
  d = {"value": 1}
  method(d)
except MyCustomException:
  print('got it')

但它不起作用!我没法发现例外。这种行为是否打破了坚实的原则,利斯科夫替代原则?在


Tags: nameselfreturninitvaluedefargsmethod
2条回答

引用文件,section 8.3

A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class).

然而,这段代码并没有破坏替换原则,因为子类当然提供了与基类相同的方法,如果它们没有以偏离基类行为的方式被重写,但您的代码不会这样做。在

顺便说一句,你不必实现任何以这种方式“重命名”类的方法。您可以简单地执行以下操作:

class MyCustomException(KeyError):
    ...

您需要显式地抛出自定义异常。在

class MyCustomException(KeyError):
  pass

def method(d):
  if not 'name' in d:
    raise MyCustomException('name not found!')
  else:
    return d['name']

try:
  d = {"value": 1}
  method(d)
except MyCustomException:
  print('got it')

Liskov替换本质上意味着:如果我有一个类,并且我将其子类化,那么这个子类应该能够以与超级类完全相同的方式工作,如果作为一个超类使用的话。在

换句话说,我创建了一个可以接受白面包和小麦面包的类Baker。如果我将Baker子类化为一个只接受白面包的类ArtisanBaker,那么我现在已经破坏了Liskov替换。我不能再把ArtisanBaker简单地用作Baker。在

相关问题 更多 >