更有用的捕获异常信息
使用except Exception as e:
捕获异常信息
>>> while True:
... try:
... x = int(input('Enter the first number:'))
... y = int(input('Enter the second number:'))
... value = x/y
... print('x/y is', value)
... except Exception as e:
... print('Invalid input:',e)
... print('please try again')
... else:
... break
...
Enter the first number:aa
Invalid input: invalid literal for int() with base 10: 'aa'
please try again
Enter the first number:1
Enter the second number:0
Invalid input: division by zero
please try again
Enter the first number:1
Enter the second number:2
x/y is 0.5
捕获异常的框架:
try:
...
except:
...
else:
...
finally:
...
继承中的super
子类继承父类时,我们经常会改写方法,但如果你仍然需要用到父类的方法或属性内容,可以使用super
>>> class Bird(object):
... def __init__(self):
... self.hungry = True
... def eat(self):
... if self.hungry:
... print('eat...')
... else:
... print('No,thanks')
...
>>> class SongBird(Bird):
... def __init__(self):
... super().__init__()
... self.sound = 'ahahah'
... def sing(self):
... print(self.sound)
...
>>> b1 = SongBird()
>>> b1.sing()
ahahah
>>> b1.eat()
eat...
property
Python内置的@property
装饰器可以把一个方法变成属性调用的。
设置方法:
@property # 获取
@方法名.setter # 设置
@方法名.deleter # 删除
>>> `c`lass Student(object):
...
... @property
... def score(self):
... return self._score
...
... @score.setter
... def score(self, value):
... if not isinstance(value, int):
... raise ValueError('score must be an integer!')
... if value < 0 or value > 100:
... raise ValueError('score must between 0 ~ 100!')
... self._score = value
...
>>> s = Student()
>>> s.score = 60 # 调用方法和设置属性一样
>>> s.score
60
一般框架如下:
class Money(object):
@property
def price(self):
...
@price.setter
def price(self,value):
...
@price.deleter
def price(self):
...
# 调用
obj.price # 获取
obj.price = 123 # 修改
del obj.price # 删除
还可以用property
函数设置:
>>> class Money(object):
... def __init__(self):
... self.money = 0
... def getmoney(self):
... return self.money
... def setmoney(self, value):
... if isinstance(value, int):
... self.money = value
... money_p = property(getmoney, setmoney)
...
>>> A = Money()
>>> A.money_p
0
>>> A.money_p = 100
>>> A.money_p
100
一般框架:
class Foo(object):
def get_bar(self):
...
def set_bar(self,value):
...
def del_bar(self):
...
BAR = property(get_bar, set_bar, del_bar, "description…")
obj = Foo()
obj.BAR
obj.BAR = "xxx"
Desc = Foo.BAR.__doc__ # 调用描述文字
del obj.BAR
静态方法和类方法
使用装饰器@staticmethod
和@classmethod
来定义,静态方法不需要传参,类方法传递参数cls
,它们的调用不需要实例化类。
>>> class Myclass:
... @staticmethod
... def smeth():
... print('This is a static method')
... @classmethod
... def cmeth(cls):
... print('This is a class method of',cls)
...
>>> Myclass.smeth()
This is a static method
>>> Myclass.cmeth()
This is a class method of <class '__main__.Myclass'>
>>>