table of Contents
01. Packaging
- Encapsulation is a major feature of object-oriented programming
- Object-oriented programming in the first step - the attributes and methods packaged into an abstract class in
- The outside world using a class to create an object , and then let the object calls methods
- Details of the method of the object are encapsulated in the interior of the class
02. Case 1_Xiao Mingai running
demand
- Xiaoming's weight
75.0
kg - Xiao Ming each runner will lose weight
0.5
kilo - Xiao Ming each eating weight gain
1
kg
Tip: In -house method object , it can attribute directly access the object 's!
- Code:
class Person:
"""人类"""
def __init__(self, name, weight):
self.name = name
self.weight = weight
def __str__(self):
return "我的名字叫 %s 体重 %.2f 公斤" % (self.name, self.weight)
def run(self):
"""跑步"""
print("%s 爱跑步,跑步锻炼身体" % self.name)
self.weight -= 0.5
def eat(self):
"""吃东西"""
print("%s 是吃货,吃完这顿再减肥" % self.name)
self.weight += 1
xiaoming = Person("小明", 75)
xiaoming.run()
xiaoming.eat()
xiaoming.eat()
print(xiaoming)
03. Case 2_ Place furniture
demand
- House (House) have units , the total area and furniture name list
- The new house has no furniture
- Furniture (HouseItem) have names and covers an area where
- Simmons (bed) covers an area of
4
square meters - Wardrobe (chest) area
2
square meter - Table (table) area
1.5
m²
- Simmons (bed) covers an area of
- The above three furniture added to the house in
- When printing a house, it is required to output: house type , total area , remaining area , list of furniture names
Remaining area
- When creating the house object is defined a property of the remaining area , the initial value is equal to the total area, and
- When you call the
add_item
method, to the room to add furniture , the let the remaining area - = furniture area
3.1 Create furniture
class HouseItem:
def __init__(self, name, area):
"""
:param name: 家具名称
:param area: 占地面积
"""
self.name = name
self.area = area
def __str__(self):
return "[%s] 占地面积 %.2f" % (self.name, self.area)
# 1. 创建家具
bed = HouseItem("席梦思", 4)
chest = HouseItem("衣柜", 2)
table = HouseItem("餐桌", 1.5)
print(bed)
print(chest)
print(table)
summary
- Created a furniture , to use
__init__
and__str__
two built-in method - Use furniture to create three furniture objects , and output information Furniture
3.2 Create a room
class House:
def __init__(self, house_type, area):
"""
:param house_type: 户型
:param area: 总面积
"""
self.house_type = house_type
self.area = area
# 剩余面积默认和总面积一致
self.free_area = area
# 默认没有任何的家具
self.item_list = []
def __str__(self):
# Python 能够自动的将一对括号内部的代码连接在一起
return ("户型:%s\n总面积:%.2f[剩余:%.2f]\n家具:%s"
% (self.house_type, self.area,
self.free_area, self.item_list))
def add_item(self, item):
print("要添加 %s" % item)
...
# 2. 创建房子对象
my_home = House("两室一厅", 60)
my_home.add_item(bed)
my_home.add_item(chest)
my_home.add_item(table)
print(my_home)
summary
- Creating a house class , to use
__init__
and__str__
two built-in method - Preparing a
add_item
method ready to add furniture - Use house class created a house Object
- Let the house objects called three times
add_item
method, the three furniture to arguments passed to theadd_item
interior
3.3 Add furniture
demand
- 1> Analyzing furniture area whether or exceeds the remaining area , if exceeded , can not be prompted to add the piece of furniture
- 2> The name of the furniture added to the furniture list of names of
- 3> with the remaining area of the house - furniture area
def add_item(self, item):
print("要添加 %s" % item)
# 1. 判断家具面积是否大于剩余面积
if item.area > self.free_area:
print("%s 的面积太大,不能添加到房子中" % item.name)
return
# 2. 将家具的名称追加到名称列表中
self.item_list.append(item.name)
# 3. 计算剩余面积
self.free_area -= item.area
3.4 Summary
- The main program is only responsible for creating house objects and furniture objects
- Let the house object call
add_item
method will be added to the house furniture in - Area calculations , the remaining area , furniture list and other processing are encapsulated into the interior of the house class
04. Case 3_ Soldier Assault
demand
- Soldier Xu Sanduo has an AK47
- Soldiers can fire
- Gun capable of launching a bullet
- Gun loading loading bullets - to increase the number of bullets
4.1 Development of guns
shoot
Method requirements
- 1> Judge whether there are bullets, you can’t shoot without bullets
- 2> use
print
tips the shooting, and outputs the number of bullets
class Gun:
def __init__(self, model):
# 枪的型号
self.model = model
# 子弹数量
self.bullet_count = 0
def add_bullet(self, count):
self.bullet_count += count
def shoot(self):
# 判断是否还有子弹
if self.bullet_count <= 0:
print("没有子弹了...")
return
# 发射一颗子弹
self.bullet_count -= 1
print("%s 发射子弹[%d]..." % (self.model, self.bullet_count))
# 创建枪对象
ak47 = Gun("ak47")
ak47.add_bullet(50)
ak47.shoot()
4.2 Develop Soldiers
Assumptions: Every recruits have no guns
Define an attribute with no initial value
When defining attributes, if anything does not know the initial value setting , it can be set toNone
None
Keyword represents nothing- Denotes a null object , no methods and properties, is a special constant
- You can be
None
assigned to any variable
fire
Method requirements
- 1> Determine whether there is a gun, you can’t charge without a gun
- 2> Shout a slogan
- 3> Loading bullets
- 4> Shooting
class Soldier:
def __init__(self, name):
# 姓名
self.name = name
# 枪,士兵初始没有枪 None 关键字表示什么都没有
self.gun = None
def fire(self):
# 1. 判断士兵是否有枪
if self.gun is None:
print("[%s] 还没有枪..." % self.name)
return
# 2. 高喊口号
print("冲啊...[%s]" % self.name)
# 3. 让枪装填子弹
self.gun.add_bullet(50)
# 4. 让枪发射子弹
self.gun.shoot()
summary
- Creating a soldier class , use the
__init__
built-in method - When defining attributes, if anything does not know the initial value setting , it can be set to
None
- In the package of internal methods, you can also make your own objects created using other classes of property calls have been packaged method
05. Identity Operator
Identity operator is used to compare two objects of memory addresses are the same - whether it is a reference to the same object
- In
Python
the ForNone
comparison, it is recommended to useis
judgment
Operator | description | Instance |
---|---|---|
is | is is to judge whether two identifiers refer to the same object | x is y,类似 id(x) == id(y) |
is not | is not is to judge whether two identifiers refer to different objects | x is not y,类似 id(a) != id(b) |
The difference between is and ==:
is
For determining two variables refer to the same whether the object
==
for determining the value of the reference variable is equal
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> b is a
False
>>> b == a
True