如何在Python类中继承错误处理
我正在编写一些样板代码,其中包含一些抽象类,其他人将从中继承。并非每个方法都需要运行,因此抽象类使用@handleError作为修饰符来处理异常 我将用狗来说明(实际问题要复杂得多)如何在Python类中继承错误处理,python,class,inheritance,abstract-class,Python,Class,Inheritance,Abstract Class,我正在编写一些样板代码,其中包含一些抽象类,其他人将从中继承。并非每个方法都需要运行,因此抽象类使用@handleError作为修饰符来处理异常 我将用狗来说明(实际问题要复杂得多) 这是异常处理装饰程序(如果无法运行,则返回None) 动物类,将从 但是,唉,现在只允许好狗: # good dog dog = Dog(4, 'woof') dog.eat_and_speak() # <-- works fine # bad dog dog = Dog('four', 'woof'
# good dog
dog = Dog(4, 'woof')
dog.eat_and_speak() # <-- works fine
# bad dog
dog = Dog('four', 'woof')
dog.eat_and_speak() # <-- raises ValueError (as 'four' isn't float)
现在允许以下坏狗处理异常:
class Dog(Animal):
def eat(self):
print('Dog eats for %0.0f seconds' % self.eat_time)
dog = Dog('four', 'woof')
dog.eat_and_speak()
> 'woof'
然而,这看起来又黑又丑
问题:类从抽象类继承错误处理的最佳方式是什么?
注意:真正的用例是一些scraper样板代码,其中一些方法可能会有错误,但是scraper应该在不返回任何错误的情况下保持运行。单个scraper的所有者将从该类继承,希望该类能够为他们处理此问题。问题似乎是您希望能够继承和重写某些内容。但是你的解决方案看起来非常直截了当,对我来说也不太老套。我会交换这些方法——修饰一个公共的
eat
,并让子类重写\u eat
——但是,是的,这看起来确实是一个不错的方法。@NathanVērzemnieks我认为用户定义公共方法会更有意义,抽象类负责处理私有类。我错了吗?
# good dog
dog = Animal(4, 'woof')
dog.eat_and_speak()
# messed up dog
dog = Animal('four', 'woof')
dog.eat_and_speak()
> 'Eats for 4 seconds'
> 'woof'
> 'woof' . # <-- yay! the messed up dog barked!
class Dog(Animal):
def eat(self):
print('Dog eats for %0.0f seconds' % self.eat_time)
# good dog
dog = Dog(4, 'woof')
dog.eat_and_speak() # <-- works fine
# bad dog
dog = Dog('four', 'woof')
dog.eat_and_speak() # <-- raises ValueError (as 'four' isn't float)
class Animal:
def __init__(self, eat_time, animal_sound):
self.sound = animal_sound
self.eat_time = eat_time
def eat(self):
print('Eats for %0.0f seconds' % self.eat_time)
def speak(self):
print(self.sound)
@handleError
def _eat(self):
self.eat()
def eat_and_speak(self):
self._eat()
self.speak()
class Dog(Animal):
def eat(self):
print('Dog eats for %0.0f seconds' % self.eat_time)
dog = Dog('four', 'woof')
dog.eat_and_speak()
> 'woof'