类
类是一种抽象出来的高级数据类型,用来定义对象属性和行为
class Ball(): #定义类名
def __init__(self): #实例化方法
self.name = '篮球' #第一个属性
self.size = '大' #第二个属性
self.color = '绿色' #第三个属性
def player(self): #普通类方法
print('打' + self.name) #输出内容
类名习惯上大写,实例化方法 __init__固定不变,可以有0个
或一个,普通类方法可以有0或多个
对象
利用类名可以创建对象,通过对象访问类中包含的属性和方法
b1 = Ball() #自动调用实例化方法,创建对象b1
b2 = Ball()#自动调用实例化方法,创建对象b2
print(b1.name+b1.size+b1.color) #访问b1属性
b2.play() #调用b2方法
类参数
类的属性值需要在创建对象时在确定,可以在定义类是运用参数
class Ball(): #定义类名
def __init__(self, n, s, c): #实例化方法
self.name = n #第一个属性
self.size = s #第二个属性
self.color = c #第三个属性
def player(self): #普通类方法
print('打' + self.name) #输出内容
b1 = Ball('篮球', '小', '绿色') #传入篮球参数
b2 = Ball('足球', '小', '白色') #传入足球参数
print(b2.color + b2.size + b2.name)
b1.player()
类和列表的结合
class Fruits( ): #定义类名
def __init__(self, name): #实例化方法,一个参数
self.name = name #参数赋值给属性
def buy(self): #普通类方法
print('买' + self.name) #方法内容
fts = [Fruits('西瓜' ),Fruits('橘子' ),Fruits('葡萄' ),Fruits('草莓' )] #创建列表并添加对象到列表
# b1 = Fruits('西瓜' ) #调用实例化方法b1
# b2 = Fruits('橘子') ##调用实例化方法b2
# b1.buy() #调用b1类方法
遍历列表中的对象
for i in range(1,8): #循环7次
fts.append(Fruits('哈密瓜' )) #列表中添加对象,循环几次添加几次
for f in fts: #列表fts中的元素依次赋值给f
print(f.name,end=' ') #f作为对象使用