- 类(Class)由三个部分构成
1)类的名称:类名
2)类的属性:一组数据
3)类的方法:允许对进行操作的方法(行为) - 举例:
1)人类设计
事物名称(类名):人(Person)
属性:身高(height),年龄(age)
方法(行为/功能):跑(run),打架(fight)
2)狗类的设计
类名:狗(Dog)
属性:品种,毛色,性别,名字,腿的数量
方法(行为/功能):叫,跑,咬人,吃,摇尾巴 - 添加属性,多个对象
class Cat:
#属性
#方法
def eat(self):
print("Cat is eating fish.")
def drink(self):
print("Cat is drinking water.")
def introduce(self):
print("%s的年龄是:%d" % (tom.name, tom.age))
#创建一个对象
tom = Cat()
#调用tom指向的对象中的方法
tom.eat()
tom.drink()
#属性就是变量
#给tom指向的对象添加2个属性
tom.name = "汤姆"
tom.age = 40
#获取属性的第一种方法
#print("%s的年龄是:%d" % (tom.name, tom.age))
tom.introduce()
lanmao = Cat()
lanmao.name = "蓝猫"
lanmao.age = 10
lanmao.introduce()
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/xinqi/PycharmProjects/test/test.py
Cat is eating fish.
Cat is drinking water.
汤姆的年龄是:40
汤姆的年龄是:40
Process finished with exit code 0
此处发现,lanmao()调用的依旧是tom.name, tome.age的值,那么如何让lanmao()调用自己的变量?如图所示流程图
self的用法
class Cat:
#属性
#方法
def eat(self):
print("Cat is eating fish.")
def drink(self):
print("Cat is drinking water.")
def introduce(self):
#print("%s的年龄是:%d" % (tom.name, tom.age))
print("%s的年龄是:%d" % (self.name, self.age))
#创建一个对象
tom = Cat()
#调用tom指向的对象中的方法
tom.eat()
tom.drink()
#属性就是变量
#给tom指向的对象添加2个属性
tom.name = "汤姆"
tom.age = 40
#获取属性的第一种方法
#print("%s的年龄是:%d" % (tom.name, tom.age))
tom.introduce() #相当于tom.introduce(tom)
lanmao = Cat()
lanmao.name = "蓝猫"
lanmao.age = 10
lanmao.introduce()
#如图所示,只需要将introduce()里面改成self.name, self.age就可以解决问题了
#self所起的作用就是谁调用就指向谁
Cat is eating fish.
Cat is drinking water.
汤姆的年龄是:40
蓝猫的年龄是:10
- "__init __"的用法
class Cat:
"""定义了一个Cat类"""
#初始化对象
def __init__(self):
print("---haha---")
#方法
def eat(self):
print("Cat is eating fish.")
def drink(self):
print("Cat is drinking water.")
def introduce(self):
print("%s的年龄是:%d" % (self.name, self.age))
#创建一个对象
tom = Cat()
tom.eat()
tom.drink()
tom.name = "汤姆"
tom.age = 40
tom.introduce()
lanmao = Cat()
lanmao.name = "蓝猫"
lanmao.age = 10
lanmao.introduce()
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/xinqi/PycharmProjects/test/test.py
---haha---
Cat is eating fish.
Cat is drinking water.
汤姆的年龄是:40
---haha---
蓝猫的年龄是:10
Process finished with exit code 0
创建对象,调用__init __方法
class Cat:
"""定义了一个Cat类"""
#初始化对象
def __init__(self, new_name, new_age):
self.name = new_name
self.age = new_age
#方法
def eat(self):
print("Cat is eating fish.")
def drink(self):
print("Cat is drinking water.")
def introduce(self):
print("%s的年龄是:%d" % (self.name, self.age))
#创建一个对象
tom = Cat("汤姆", 40)
#tom = Cat()
tom.eat()
tom.drink()
#tom.name = "汤姆"
#tom.age = 40
tom.introduce()
#lanmao = Cat()
lanmao = Cat("蓝猫", 10)
#lanmao.name = "蓝猫"
#lanmao.age = 10
lanmao.introduce()
这个程序中,可以直接在tom = Cat()和lanmao = Cat里面赋值,将"汤姆""蓝猫"赋值给new_name,将40, 10赋值给new_age,每次创建两个不同的对象,之后调用__init __()方法,最后返回这个对象的引用
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/xinqi/PycharmProjects/test/test.py
Cat is eating fish.
Cat is drinking water.
汤姆的年龄是:40
蓝猫的年龄是:10
Process finished with exit code 0
-
"__str __"方法的作用
调用__str__方法.png
class Cat:
"""定义了一个Cat类"""
#初始化对象
def __init__(self, new_name, new_age):
self.name = new_name
self.age = new_age
def __str__(self):
return "%s的年龄是:%d" % (self.name, self.age)
#方法
def eat(self):
print("Cat is eating fish.")
def drink(self):
print("Cat is drinking water.")
def introduce(self):
print("%s的年龄是:%d" % (self.name, self.age))
#创建一个对象
tom = Cat("汤姆", 40)
lanmao = Cat("蓝猫", 10)
print(tom)
print(lanmao)
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/xinqi/PycharmProjects/test/test.py
汤姆的年龄是:40
蓝猫的年龄是:10
Process finished with exit code 0
- 烤地瓜程序
"""烤地瓜程序"""
"""示例属性如下"""
#cookedLevel: 0~3表示还是生的,超过3表示半生不熟,超过5表示已经烤好了,超过8表示已经烤成木炭了
#地瓜开始的时候是生的
#cookedString: 这是字符串,描述地瓜的生熟程度
#condiments: 这是地瓜的配料列表,比如蕃茄酱、芥末酱等
class SweetPotato:
def __init__(self):
self.cookedString = "生的"
self.cookedLevel = 0
def __str__(self):
return "地瓜 状态:%s(%d)" % (self.cookedString, self.cookedLevel)
def cook(self, cooked_time):
if cooked_time >= 0 and cooked_time < 3:
self.cookedString = "生的"
elif cooked_time >= 3 and cooked_time < 5:
self.cookedString = "半生不熟"
elif cooked_time >= 5 and cooked_time < 8:
self.cookedString = "熟了"
elif cooked_time > 8:
self.cookedString = "烤糊了"
#创建了一个地瓜对象
di_gua = SweetPotato()
#开始烤地瓜
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/xinqi/PycharmProjects/test/test.py
地瓜 状态:生的(0)
地瓜 状态:生的(0)
地瓜 状态:生的(0)
地瓜 状态:生的(0)
地瓜 状态:生的(0)
Process finished with exit code 0
此处我们发现,结果并没有累加上去,跟我们预期的每次烤一分钟,五次就是烤了五分钟的结果不一样,那么如何改进呢?
"""烤地瓜程序"""
"""示例属性如下"""
#cookedLevel: 0~3表示还是生的,超过3表示半生不熟,超过5表示已经烤好了,超过8表示已经烤成木炭了
#地瓜开始的时候是生的
#cookedString: 这是字符串,描述地瓜的生熟程度
#condiments: 这是地瓜的配料列表,比如蕃茄酱、芥末酱等
class SweetPotato:
def __init__(self):
self.cookedString = "生的"
self.cookedLevel = 0
def __str__(self):
return "地瓜 状态:%s(%d)" % (self.cookedString, self.cookedLevel)
def cook(self, cooked_time):
self.cookedLevel += cooked_time
if self.cookedLevel >= 0 and self.cookedLevel < 3:
self.cookedString = "生的"
elif self.cookedLevel >= 3 and self.cookedLevel < 5:
self.cookedString = "半生不熟"
elif self.cookedLevel >= 5 and self.cookedLevel < 8:
self.cookedString = "熟了"
elif self.cookedLevel > 8:
self.cookedString = "烤糊了"
#创建了一个地瓜对象
di_gua = SweetPotato()
#开始烤地瓜
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/xinqi/PycharmProjects/test/test.py
地瓜 状态:生的(1)
地瓜 状态:生的(2)
地瓜 状态:半生不熟(3)
地瓜 状态:半生不熟(4)
地瓜 状态:熟了(5)
地瓜 状态:熟了(6)
地瓜 状态:熟了(7)
地瓜 状态:熟了(8)
地瓜 状态:烤糊了(9)
地瓜 状态:烤糊了(10)
地瓜 状态:烤糊了(11)
Process finished with exit code 0
添加佐料
"""烤地瓜程序"""
"""示例属性如下"""
#cookedLevel: 0~3表示还是生的,超过3表示半生不熟,超过5表示已经烤好了,超过8表示已经烤成木炭了
#地瓜开始的时候是生的
#cookedString: 这是字符串,描述地瓜的生熟程度
#condiments: 这是地瓜的配料列表,比如蕃茄酱、芥末酱等
class SweetPotato:
def __init__(self):
self.cookedString = "生的"
self.cookedLevel = 0
self.condiments = []
def __str__(self):
return "地瓜 状态:%s(%d),添加的佐料有:%s" % (self.cookedString, self.cookedLevel, str(self.condiments))
def cook(self, cooked_time):
self.cookedLevel += cooked_time
if self.cookedLevel >= 0 and self.cookedLevel < 3:
self.cookedString = "生的"
elif self.cookedLevel >= 3 and self.cookedLevel < 5:
self.cookedString = "半生不熟"
elif self.cookedLevel >= 5 and self.cookedLevel < 8:
self.cookedString = "熟了"
elif self.cookedLevel > 8:
self.cookedString = "烤糊了"
def addCondiments(self, item):
self.condiments.append(item)
#创建了一个地瓜对象
di_gua = SweetPotato()
#开始烤地瓜
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
di_gua.addCondiments("Garlic")
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
di_gua.addCondiments("Pepper")
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
di_gua.addCondiments("Butter")
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
di_gua.addCondiments("Ketchup")
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/xinqi/PycharmProjects/test/test.py
地瓜 状态:生的(1),添加的佐料有:[]
地瓜 状态:生的(2),添加的佐料有:[]
地瓜 状态:半生不熟(3),添加的佐料有:['Garlic']
地瓜 状态:半生不熟(4),添加的佐料有:['Garlic']
地瓜 状态:熟了(5),添加的佐料有:['Garlic', 'Pepper']
地瓜 状态:熟了(6),添加的佐料有:['Garlic', 'Pepper']
地瓜 状态:熟了(7),添加的佐料有:['Garlic', 'Pepper', 'Butter']
地瓜 状态:熟了(8),添加的佐料有:['Garlic', 'Pepper', 'Butter']
地瓜 状态:烤糊了(9),添加的佐料有:['Garlic', 'Pepper', 'Butter', 'Ketchup']
地瓜 状态:烤糊了(10),添加的佐料有:['Garlic', 'Pepper', 'Butter', 'Ketchup']
地瓜 状态:烤糊了(11),添加的佐料有:['Garlic', 'Pepper', 'Butter', 'Ketchup']
Process finished with exit code 0
- 存放家具程序
这个程序的目的是把一个对象放到另一个对象里面去
class Home:
def __init__(self, new_area, new_info, new_addr):
self.area = new_area
self.info = new_info
self.addr = new_addr
self.left_area = new_area
self.contain_items = []
def __str__(self):
msg = "房子的总面积是:%d,可用面积是:%d, 户型是:%s,地址是:%s" % (self.area, self.left_area, self.info, self.addr)
msg += " 当前房子里的物品有%s" % str(self.contain_items)
return msg
def add_item(self, item):
self.left_area -= item.area
self.contain_items.append(item.name)
class Bed:
def __init__(self, new_name, new_area):
self.name = new_name
self.area = new_area
def __str__(self):
return "%s占用的面积是:%d" % (self.name, self.area)
house = Home(129, "三室一厅", "Sydney")
print(house)
bed1 = Bed("席梦思", 4)
print(bed1)
house.add_item(bed1)
print(house)
bed2 = Bed("三人床", 6)
house.add_item(bed2)
print(house)
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/xinqi/PycharmProjects/test/test.py
房子的总面积是:129,可用面积是:129, 户型是:三室一厅,地址是:Sydney 当前房子里的物品有[]
席梦思占用的面积是:4
房子的总面积是:129,可用面积是:125, 户型是:三室一厅,地址是:Sydney 当前房子里的物品有['席梦思']
房子的总面积是:129,可用面积是:119, 户型是:三室一厅,地址是:Sydney 当前房子里的物品有['席梦思', '三人床']
Process finished with exit code 0
这个程序还可以做进一步的改进
class Home:
def __init__(self, new_area, new_info, new_addr):
self.area = new_area
self.info = new_info
self.addr = new_addr
self.left_area = new_area
self.contain_items = []
def __str__(self):
msg = "房子的总面积是:%d,可用面积是:%d, 户型是:%s,地址是:%s" % (self.area, self.left_area, self.info, self.addr)
msg += " 当前房子里的物品有%s" % str(self.contain_items)
return msg
def add_item(self, item):
self.left_area -= item.get_area()
self.contain_items.append(item.get_name())
#self.left_area -= item.area
#self.contain_items.append(item.name)
class Bed:
def __init__(self, new_name, new_area):
self.name = new_name
self.area = new_area
def __str__(self):
return "%s占用的面积是:%d" % (self.name, self.area)
def get_area(self):
return self.area
def get_name(self):
return self.name
house = Home(129, "三室一厅", "Sydney")
print(house)
bed1 = Bed("席梦思", 4)
print(bed1)
house.add_item(bed1)
print(house)
bed2 = Bed("三人床", 6)
house.add_item(bed2)
print(house)
此时可以对item.area和item.name进行一个封装,因为这样可以保证信息的安全行,而不至于别人想调用自己的item.area就可以直接看到我自己的数据。具体可以用一个get_area()和item.get_name()函数调用一下,并且在Bed的class里面定义这两个函数。