1.判断类型
isinstance( x,int) 判断x 是否为整型
isinstance( x,str) 判断x 是否为字符串
2.判断一个数开根号是否为整数
r=int(math.sqrt(x))
r*r==x
3. python 判断list中是否包含一个元素
pythontab = ['p','y','t','h','o','n','t','a','b']
if 't' in pythontab:
print 't in pythontab'
if 'w' not in pythontab:
print 'w is not in pythontab'
列表使用 [ ] 包裹
都可使用 [ : ]来得到切片内容
元组的区别是内容不可修改,可看成只读列表
if 't' in pythontab:
print 't in pythontab'
if 'w' not in pythontab:
print 'w is not in pythontab'
4.元组和列表区别
元组使用 ()包裹列表使用 [ ] 包裹
都可使用 [ : ]来得到切片内容
元组的区别是内容不可修改,可看成只读列表
5.python @property
因为Python支持高阶函数,在函数式编程中我们介绍了装饰器函数,可以用装饰器函数把 get/set 方法“装饰”成属性调用:
class Student(object):
def __init__(self, name, score):
self.name = name
self.__score = score
@property
def score(self):
return self.__score
@score.setter
def score(self, score):
if score < 0 or score > 100:
raise ValueError('invalid score')
self.__score = score
注意: 第一个score(self)是get方法,用@property装饰,第二个score(self, score)是set方法,用@score.setter装饰,@score.setter是前一个@property装饰后的副产品。