繁体   English   中英

python中的类构造函数内部的异常处理

[英]Exception handling inside class constructor in python

我正在解决一本初学者python书中的小练习。 我必须用三个类型分别为strintfloat实例变量创建一个Flower类,分别代表花朵的名称,花瓣数量和价格。 我还必须包括用于设置每种类型的值并检索每种类型的值的方法。 我知道用户可以在实例变量中输入他喜欢的任何类型。 例如,他可以将花瓣数作为str而不是int传递给Flower实例。 为了避免这些问题,我在类方法中包括了简单的try/except块。 下面是一个工作示例:

class Flower:
    """A flower."""

    def __init__(self, name, petals, price):
        """Create a new flower instance.

        name    the name of the flower (e.g. 'Spanish Oyster')
        petals  the number of petals exists (e.g. 50)
        price   price of each flower (measured in euros)
        """
        self._name = str(name)
        self._petals = petals
        self._price = price

    def set_name(self, name):
        self._name = str(name)

    def get_name(self):
        return self._name

    def set_petals(self, petals):
        try:
            self._petals = int(petals, 10)
        except ValueError:
            print('set_petals(): could not parse "%s" to int().' % petals)

    def get_petals(self):
        return self._petals

    def set_price(self, price):
        try:
            self._price = float(price)
        except ValueError:
            print('set_price(): You should parse "%s" to float().' % price)

    def get_price(self):
        return self._price


if __name__ == '__main__':
    rose = Flower('Rose', 60, 1.3)

    print('%s contains %d petals costs %.2f euros.' % \
            (rose.get_name(), rose.get_petals(), rose.get_price()))

    rose.set_petals('error')


    """Initialize a new Flower instance with false values."""
    sunflower = Flower('Sunflower', 'error', 'another error')

    print('%s contains %d petals costs %.2f euros.' % \
            (sunflower.get_name(), sunflower.get_petals(), \
            sunflower.get_price()))

说明

让我们考虑一个用户初始化一个新的Flower实例:

rose = Flower('Rose', 60, 1.3)

然后,他想更新花瓣的数量,因此他调用set_petals()方法:

rose.set_petals('error')

我的异常处理块捕获并打印:

set_petals(): could not parse "error" to int().

相同的逻辑适用于set_price()方法。

现在考虑他将这些错误值传递给构造函数。

sunflower = Flower('Sunflower', 'error', 'another error')

在构造函数中,正如您在我的代码中看到的那样,我不检查类型错误,因此,当我要打印sunflower实例的值时,这就是执行第二次print时在输出中得到的内容:

TypeError: %d format: a number is required, not str

问题

我试图完成的工作是在构造函数中也输入这些类型检查。 但是,我是python的新手,不知道最好的方法是什么来保持适当的抽象级别并且不违反DRY原理。 一种想法是在构造函数中编写try/except块,但这会使我的代码不知所措。 另一个想法是将错误处理分为不同的功能。 如何正确处理这些类型检查?

只需执行以下操作:

   def __init__(self, name, petals, price):
        """Create a new flower instance.

        name    the name of the flower (e.g. 'Spanish Oyster')
        petals  the number of petals exists (e.g. 50)
        price   price of each flower (measured in euros)
        """
        self._name = str(name)
        self.set_petals(petals)
        self.set_price(price)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM