python中类构造函数内部的异常处理
我正在解决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."""
Flower
,其中包含类型为str
、int
和float
的三个实例变量,分别表示花的名称、花瓣数和价格。我还必须包括设置每种类型的值和检索每种类型的值的方法。我知道用户可以在实例变量中输入他喜欢的任何类型。例如,他可以将花瓣数作为str
而不是int
传递给Flower
实例。为了避免这些问题,我在类方法中包含了simpletry/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)
有趣的是,我发现了两个看似矛盾的答案:非常感谢。我现在查看链接。有趣的是,我发现了两个看似矛盾的答案:非常感谢。我现在查看链接。这是我很好奇的事情,但不知道如何搜索它。非常感谢。这是我很好奇的事情,但我不知道如何搜索它。非常感谢你。