python学习笔记(异常、继承中的super、property、静态方法和类方法)

更有用的捕获异常信息

使用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'>
>>> 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值