class Flower:
def __init__(self, name, petals, price):
self.name = name
try:
petals = int(petals)
except:
print("There is an error.")
self.petals = petals
try:
price = float(price)
except:
print("There is an error.")
self.price = price
def get_name(self):
if self.name is None:
return ('No Attribute')
else:
return self.name
def get_petals(self):
if self.petals is None:
return ('No Attribute')
else:
return self.petals
def get_price(self):
if self.price is None:
return ('No Attribute')
else:
return self.price
flower1= Flower('Rose','100.798','100')
print(flower1.petals)
发布于 2021-11-08 09:38:20
当发生异常时,您需要做一些事情来控制分配给相应实例属性(self.petals
或self.price
)的值。这说明了我的意思:
class Flower:
def __init__(self, name, petals, price):
self.name = name
try:
petals = int(petals)
except ValueError:
print("There is an error:")
petals = ''
self.petals = petals
try:
price = float(price)
except ValueError:
print("There is an error:")
price = ''
self.price = price
def get_name(self):
if self.name is None:
return ('No Attribute')
else:
return self.name
def get_petals(self):
if self.petals is None:
return ('No Attribute')
else:
return self.petals
def get_price(self):
if self.price is None:
return ('No Attribute')
else:
return self.price
flower1= Flower('Rose','100.798','100')
print(flower1.petals)
https://stackoverflow.com/questions/69887520
复制相似问题