Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中类构造函数内部的异常处理_Python_Python 3.x_Oop_Exception Handling - Fatal编程技术网

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

python中类构造函数内部的异常处理,python,python-3.x,oop,exception-handling,Python,Python 3.x,Oop,Exception Handling,我正在解决python初学者书中的一个小练习。我必须创建一个类Flower,其中包含类型为str、int和float的三个实例变量,分别表示花的名称、花瓣数和价格。我还必须包括设置每种类型的值和检索每种类型的值的方法。我知道用户可以在实例变量中输入他喜欢的任何类型。例如,他可以将花瓣数作为str而不是int传递给Flower实例。为了避免这些问题,我在类方法中包含了simpletry/except块。下面是一个工作示例: class Flower: """A flower."""

我正在解决python初学者书中的一个小练习。我必须创建一个类
Flower
,其中包含类型为
str
int
float
的三个实例变量,分别表示花的名称、花瓣数和价格。我还必须包括设置每种类型的值和检索每种类型的值的方法。我知道用户可以在实例变量中输入他喜欢的任何类型。例如,他可以将花瓣数作为
str
而不是
int
传递给
Flower
实例。为了避免这些问题,我在类方法中包含了simple
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()))
解释

让我们考虑一个用户初始化一个新的代码>花<代码>实例:

rose = Flower('Rose', 60, 1.3)
然后他想更新花瓣的数量,所以他调用
set\u petals()
method:

rose.set_petals('error')
我的异常处理块捕获并打印:

set_petals(): could not parse "error" to int().
同样的逻辑也适用于
set\u price()
方法

现在考虑他把那些错误的值传递给构造函数。

sunflower = Flower('Sunflower', 'error', 'another error')
在构造函数中,正如您在我的代码中看到的,我不检查类型错误,因此当我要从
sunflower
实例打印值时,这是我在执行第二个
打印时在输出中得到的:

TypeError: %d format: a number is required, not str
问题 我试图完成的是在构造函数中输入这些类型检查。然而,我是python新手,不知道保持适当的抽象级别和不违反原则的最佳方法是什么。一个想法是在构造函数中编写
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)
只需这样做:

   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)

有趣的是,我发现了两个看似矛盾的答案:非常感谢。我现在查看链接。有趣的是,我发现了两个看似矛盾的答案:非常感谢。我现在查看链接。这是我很好奇的事情,但不知道如何搜索它。非常感谢。这是我很好奇的事情,但我不知道如何搜索它。非常感谢你。