推导式创建二维列表
a=[[1,2,3],[4,5,6],[7,8,9]]
b=[a[i][j] for i in range(len(a)) for j in range(len(a[i]))]
print(b)
a=[[3*i+1+j for j in range(3)] for i in range(3)]
print(a)
a=[[4*i+1+j for j in range(4)] for i in range(4)]
print(a)
映射与筛选
a=[1,2,3,4,5]
b=filter(lambda x:True if x%2==0 else False,a)
print(*b)
def xx(x):
return x*2
b=map(xx,a)
print(*b)
Python中的类
class A():
def __init__(self,name,age,sex,score):
print(name)
self.name=name
self.age=age
self.sex=sex
self.score=score
def show(self):
print("我叫{},是{}生,今年{}岁,成绩{}".format(self.name,self.age,self.sex,self.score))
def sleep(self):
print("Zzz")
def eat(self):
print("enough")
t1=A('阿萨德','女',17,24)
t1.name='123'
t1.show()
t1.sleep()
t1.eat()
print(id(t1))
t2=A('sdf','女',17,24)
t2.show()
t2.sleep()
t2.eat()
print(id(t2))
创建类及对象时的注意事项
class St():
c=0
cg=0
def __init__(self,name):
self.name=name
St.c+=1
def sdf(self):
print(self.name)
a=St('1')
b=St('2')
a.c=a.c+5 #a.c(开辟新的内存空间给对象a的独有变量c)=(等号相当于开辟新的内存空间)a.c(使用类St的变量C)+5
print(a.c)
print(St.c)
del a.c#删除对象a的属性变量c
print(a.c)#此时对象a没有变量c,使用类的属性变量c
类中列表追加元素
class A():
listA=[1,2,3]
def __init__(self,name):
# self.listA=[1,2,3]
self.name=name
zs=A('sd')
# zs.listA=[5,9]
zs.listA.append(4)
A.listA.append(5)
print(zs.listA)
print(A.listA)
对象方法、类的方法、静态方法
class A():
a=4
def __init__(self,name):
self.name=name
def sh(self):#实例方法/对象方法
print(self.name)
@classmethod #类方法
def cc(cls):
print(cls.a,A.a)
@staticmethod
def xc(a,b):
print(a+b)
print("到此一游")
def as1(self):
print(self.name)
A.cc()
A.xc(3,4)
t=A('集合')
t.as1()
作业1
# 面向对象中 属性的练习
"""
邓超 体重 75.0 公斤
邓超每次 奔跑 会减肥 0.1 公斤
邓超每次 吃东西 体重增加 0.5 公斤
"""
class humen():
def __init__(self,weight):
self.weight=weight
def run(self):
self.weight-=0.1
print(self.weight,"公斤")
def eat(self):
self.weight+=0.5
print(self.weight,"公斤")
dengchao=humen(75)
dengchao.run()
dengchao.eat()
作业2
两个类配合使用练习
"""
需求
狙击手 麦克 有一把 狙M99
麦克 可以 开火
狙M99 能够 发射 子弹
狙M99 装填 装填子弹 —— 增加子弹数量
"""
class Gun():
bullet=0
def __init__(self,gunmodel):
self.gunmodel=gunmodel
def shoot(self):
if Gun.bullet==0:
print("没有子弹")
self.addbullet()
print('装弹',Gun.bullet)
while Gun.bullet>0:
Gun.bullet-=1
print('射击',Gun.bullet)
def addbullet(self):
Gun.bullet+=50
class Guner():
def __init__(self,name):
self.name=name
def openfire(self):
u=Gun('狙M99')
u.shoot()
a=Guner('Mike')
a.openfire()
作业3
from random import *
class A():
score=0
def __init__(self,player):
self.player=player
@classmethod
def xx(cls):
print("游戏开始")
A.score=randint(1,10)
@classmethod
def yy(cls):
if A.score<=4:
print('游戏失败')
else:
print("获胜")
@staticmethod
def zz(a,b):
print("{}的得分为{}".format(a,b))
a1=A('小明')
A.xx()
A.yy()
a1.zz(a1.player,a1.score)