您的位置:首页 > 编程语言 > Python开发

python基础--零散知识点

2018-03-28 19:50 501 查看
1.生成器
假设一个列表的存有 数量很大的元素,但是在每一次运行时,通常只调用前面几个元素,这时为了优化,可以采用生成器.isList = [x * x for x in range(10)]
print(isList) # 结果[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

isGenerator = (x * x for x in range(10))
print(isGenerator) # 这里显示的结果是生成器的地址<generator object <genexpr> at 0x0000028E39D79938>

print("result : %d " % next(isGenerator)) # result : 0
print("result : %d " % next(isGenerator)) # result : 1
print("result : %d " % next(isGenerator)) # result : 4

for i in isGenerator:
print(i) # 依次是 9, 16, 25, 36, 49, 64, 81

for it in isGenerator:
print("this time : %d" % it) # 结果为空,这时如果继续调用next(isGenerator),会报StopIteration(因为越界).2.静态方法通过  @staticmethod  即可把其装饰的方法变为一个静态方法,静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法。class People:
def __init__(self,name):
self.name=name

@staticmethod
def man(self):
print("i am a man %s" %self.name)

p=People('n')
p.man(p) # 因为在第6行传入的参数是self(类里的变量),所以在调用的时候不能写成 p=People() ,要传入 对象 p ,这样才不会报错

# 结果 i am a man n或者写成
class People:
def __init__(self,name):
self.name=name

@staticmethod
def man():
print("i am a man ")

p=People('n')
p.man()  # 因为在第6行没有传入参数,所以在调用的时候就不能访问类里的变量

# 结果 i am a man

3.类方法类方法通过  @classmethod  实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量class People:
age = 23
def __init__(self,name):
self.name=name

@classmethod
def man(self):
print("i am a man %d" % self.age)

p=People('n')
p.man() # 如果在第8访问的是 self.name,就会报错,因为其是 实例变量

# 结果 i am a man 23
如有不对,还望大佬们多多指教.  我的博客园链接:点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python