Python从list类型、range()序列简单认识类(class)【可迭代】
本文实例讲述了Python从list类型、range()序列简单认识类(class)。分享给大家供大家参考,具体如下:
list类型
定义:
items=[]
这就定义了一个名叫items的list。
往里填充数据:
items.append(1) items.append(3) items.append(4) print(items)#[1,3,4]
range序列
上面那个list,如果我们要append进去0~9的数字。最好是利用循环。
items=[] forxinrange(0,10): items.append(x) print(items)#[0,1,2,3,4,5,6,7,8,9]
这里我们就学到了range这个类型,range(0,10)包含0不包含10,可以简写为range(10)。
上面还可以这样写:
items=[xforxinrange(10)] print(items)#[0,1,2,3,4,5,6,7,8,9]
range()还有第三个参数:步长
#从0到10,步长为2 items=[xforxinrange(0,10,2)] print(items)#[0,2,4,6,8]
每个元素都x3:
items=[x*3forxinrange(0,10,2)] print(items)#[0,6,12,18,24]
每个元素都二次方:
items=[x**2forxinrange(0,10,2)] print(items)#[0,4,16,36,64]
什么叫iterable可迭代
简单说就是可以进行for循环的。
字符串、list类型、字典类型、元组类型,包括自定义的类都是可以迭代。
Python里的类
#自定义类 classPerson: #类似构造函数 def__init__(self,name): self.name=name defshow(self): print(self.name) #实例化类 p=Person("jack") p.show()#jack
注意:self可以换成任意如abc。
如何写静态方法?
#自定义类 classPerson: @staticmethod defversion(): print("version1.0")
@staticmethod是注解。(是不是和Java很像?)
#实例化类 Person.version()#version1.0
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。