008. Object oriented encapsulation cases

Keywords: Programming Attribute Python

Object oriented encapsulation case

  • Encapsulation is a major feature of object-oriented programming
  • The first step of object-oriented programming -- encapsulating properties and methods into an abstract class
  • Objects are created using classes, and then objects call methods
  • The details of the object are encapsulated inside the class

Tip: inside the method of an object, you can directly access the properties of the object.

# case

class Person:
    
    def __init__(self, name, weight):
        
        # self. Attribute = formal parameter
        self.name = name
        self.weight = weight
        
    def __str__(self):
        
        return "My name is %s Weight is %.2f" %(self.name, self.weight)
    
    def run(self):
        print("%s Love running, exercise" % self.name)
        self.weight -= 0.5 
    
    def eat(self):
        print("%s It's food. Lose weight after this meal" %self.name)
        self.weight += 1
    
xiaoming = Person("Xiao Ming", 75.0)

xiaoming.run()
xiaoming.eat()

print(xiaoming)

Xiaoming loves running and exercises
Xiaoming is a foodie. He will lose weight after eating this meal
My name is Xiaoming. My weight is 75.50

Tips:

  • Within the method of an object, you can directly access the properties of the object
  • The attributes of multiple objects created by the same class do not interfere with each other.
xiaomei = Person("Xiaomei", 45.0)
xiaomei.run()
xiaomei.eat()
print(xiaomei)
print(xiaoming)

Xiaomei loves running and exercises
Xiaomei is a foodie. She will lose weight after eating this meal
My name is Xiaomei. My weight is 45.50
My name is Xiaoming. My weight is 75.50

# Cases, used classes are usually developed first
# Furniture category
class HouseItem:
    
    def __init__(self, name, area):
        
        self.name = name
        self.area = area
        
    def __str__(self):
        
        return "[%s]Land occupation %.2f" %(self.name, self.area)
    

class House:
    
    def __init__(self, house_type, area):
        
        self.house_type = house_type
        self.area = area
        
        # Residual area
        self.free_area = area
        
        # Furniture name list
        self.item_list = []
        
    def __str__(self):
        
        #python can automatically connect the code inside a pair of brackets together
        return ("Apartment layout: %s \n Total area:%.2f \n [Surplus:%.2f]\n Furniture:%s" 
               % (self.house_type, self.area, 
                  self.free_area, self.item_list))
    
    def add_item(self, item):
        print("To add %s" % item)
        # 1. Judge furniture area
        if item.area > self.free_area:
            print("{} The area of is too large to add".format(item.name))
            
            return
        # 2. Add furniture name to furniture list
        self.item_list.append(item.name)
        # 3. Calculate the remaining area
        self.free_area -= item.area
    
# 1. Create furniture

bed = HouseItem("Simmons", 100)
chest = HouseItem("Wardrobe", 2)
table = HouseItem("table", 1.5)
print(bed)
print(chest)
print(table)

# 2. Create a house object

my_home = House("two bedrooms", 60)

my_home.add_item(bed)
my_home.add_item(chest)
my_home.add_item(table)

print(my_home)

[Simmons] 100.00
[wardrobe] 2.00
[dining table] 1.50
To add [Simmons] cover an area of 100.00
The area of Simmons is too large to add
To add [wardrobe] floor space 2.00
To add a 1.50 floor area
House type: two rooms and one hall
Total area: 60.00
[remaining: 56.50]
Furniture: [wardrobe, dining table]

#Case 2

class Gun:
    
    def __init__(self, model):
        
        # 1. Grab model
        self.model = model
        
        #2. Number of bullets
        self.bullet_count = 0
        
    def add_bullet(self, count):
        
        self.bullet_count += count
        
    def shoot(self):
        
        # 1. Judge the number of bullets
        if self.bullet_count <= 0:
            print("{}No more bullets...".format(self.model))
            
            return
        #2. Firing bullets
        self.bullet_count -= 1
        
        #3. Prompt launch information
        print("{} Protrusion...{}" .format(self.model, self.bullet_count))
        
        
        
class Soldier:
    
    def __init__(self, name):
        
        #1. name
        self.name = name
        
        #2. Guns - recruits don't have guns
        # When defining an attribute, if you don't know what value to assign, use None instead
        self.gun = None
        
    def fire(self):
        
        #1. Judge whether soldiers have guns
        #if self.gun == None:
        # When using None for judgment, you need to use is for specification instead of = =, for judgment.
        if self.gun is None:
            print("{}No guns....".format(self.name))
            
            return
        #2. Shout slogans
        print("Rush!...{}".format(self.name))
        
        #3. Fill the gun with bullets
        self.gun.add_bullet(50)
        
        #4. Let the gun shoot
        self.gun.shoot()
        
# The properties of an object that can be created by another class.       
# 1. Create gun object
ak47 = Gun("AK47")

#2. Create Xu Sanduo
xusanduo = Soldier("Xu sando")

xusanduo.gun = ak47
xusanduo.fire()

print(xusanduo.gun)

Rush... Xu sando
AK47 protrusion Forty-nine
<main.Gun object at 0x030D0E30>

Published 8 original articles, praised 0, visited 117
Private letter follow

Posted by journeyman73 on Sat, 07 Mar 2020 04:23:36 -0800