Python_ Encapsulation case (soldier assault)

1. Requirement analysis - attributes can be objects created by another class

 

The properties of an object can be objects created by another class.

Xu Sanduo is a Soldier, so we need to define a Soldier class Soldier, and AK47 is a Gun, so we also need to define a Gun class. After the two classes are determined, we will look at the requirements. Having an AK47 means that Xu Sanduo should have a Gun attribute, and this AK47 should be an object created by Gun gun.

Soldier Xu Sanduo's gun(AK47) attribute uses the object created by the gun class. Soldiers can fire, and guns can fire bullets. When soldiers fire, Xu Sanduo lifts gun(AK47) and pulls the trigger. This is the action of firing, while guns fire bullets to fire bullets. Therefore, we need to define a firing method in the soldier class, and in the gun class, Define a firing method. The gun fires bullets and the soldier fires and pulls the trigger. The actions of the two methods are different

In order to simplify the case drill, the bullet class is not considered for the time being, and only the number of bullets is considered. If the gun wants to launch bullets, there should be a sufficient number of bullets. Therefore, we also need to define the attribute of bullet number in the gun class, and add a method of loading bullets to the gun_ Bullet, we pass this method a count of bullets to be loaded, which can modify the number of bullets contained in the gun object. When the gun has enough bullets, it can launch

The above is what we need to do in the case of soldier assault

We should develop the gun class first, and the gun class should be used first. Otherwise, when we develop the soldier class, if there is no gun class, the soldier's attributes cannot be defined. Therefore, we should focus on the development of the gun class first

2. Create gun class

Use the class keyword to create a gun class, and then use the def keyword to define the initialization method. The initialization method can simplify the creation of objects. Two attributes need to be defined in the gun class, model and bullet_count .

The first attribute model should be passed by the outside world, and the second attribute bullet quantity_ Count, suppose that every time we create a gun object, the initial number of bullets is 0. If the gun wants to fire bullets, it must call the method of loading bullets to fire. From this point of view, the attribute of bullet number does not need to be defined as a formal parameter of the initialization method (that is, passed by the outside world)

Add a formal parameter of model to the initialization method, and then define two attributes in the initialization method. The first attribute is the model of the gun, and the second attribute specifies the number of bullets bullet_count.

Use self.model   = Model, pass the formal parameter model to the attribute, and then define the bullet number_ Count attribute, and initially set the number of bullets of the gun to 0, so that an initialization method is completed

There is a bullet loading method in the gun class. This method needs to receive a count parameter, because we need to use this parameter to modify the bullet quantity_ Count this attribute

Use the def keyword to define a method to add bullets. This method only needs to increase the bullet count attribute. Then we will make the bullet count bullet inside the method_ Count is added to the formal parameter count passed in, self.bullet_count += count, so the method of loading bullets is finished

The gun should be able to fire bullets. As long as the number of bullets is enough, the gun can fire bullets. Therefore, the shot method does not need to pass any parameters. Then use the def keyword to define a shot method. This method does not need to pass additional parameters

The gun should do three things to fire bullets. The first thing is to judge the number of bullets. The second thing is to fire bullets. After each bullet is fired, the number of bullets should be reduced by 1. The third thing is to prompt the launch information after the bullet is fired

The first thing is to write an if to judge the bullet quantity attribute of the gun object. If the bullet quantity is < = 0, it cannot be fired. Use the print function to make an output, print("[%s] no bullets...% self.model). If there are no bullets, the code in the second and third steps below does not need to be executed. Since the code below does not need to be executed, We can use the return keyword to return directly

Second, to fire bullets, reduce the number of bullets by 1, self.bullet_count -= 1. The number of bullets is modified

In step 3, we use the print function to make an output. print("[%s] Tu Tu... [% D]"% (self. Model, self. Bullet)_ Count), the first format operator, we should pass in the model, and the second format operator should pass in the number of remaining bullets, self.bullet_count.

After the above three steps, a launch method is also completed

After the gun class is completed, we can create the gun object in the main program

Create a gun object AK47, first let it call the bullet loading method, specify 50 bullets, and then let it call the firing method, AK47. Shot(), the console outputs "[AK47] Tu Tu... [49]", fires 1 bullet, and the remaining 49 bullets

class Gun:


    def __init__(self, model):
        #1. model of gun
        self.model = model

        #2. Number of bullets. Set the initial value of the number of bullets of the gun to 0
        self.bullet_count = 0

    # Define a bullet loading method. Pass in the formal parameter count to represent the bullet loading method 
    def add_bullet(self, count):

        self.bullet_count += count

    # Define how a gun fires bullets
    def shoot(self):
        # 1. Judge the number of bullets. Only when there are enough bullets can bullets be fired
        if self.bullet_count <= 0:
            print("[%s] There are no bullets..." % self.model)

            return
        # 2. Fire the bullet. After firing the bullet, let the bullet do a minus 1 operation
        self.bullet_count -= 1

        # 3. Prompt the firing information and put the gun model and the remaining bullet_count makes an output
    
        print("[%s] Protrusion...[%d]" % (self.model, self.bullet_count))

# After the gun class has been created, you can create a gun object in the main program

# 1. Create a gun object and create an object called ak47
ak47 = Gun("AK47")

# Load ak47 up
ak47.bullet_count(50)

# Use ak47 to fire bullets
ak47.shoot()




Operation results:

 

3. Create a soldier class_ Complete initialization method

 

Next, set the soldier class. In the initialization method of the soldier class, we define two attributes for the soldier, a name and a gun gun,

Assuming that every recruit doesn't have a gun, we need to use the assignment statement in the initialization method to define the attribute of the gun. However, if the recruit doesn't have a gun, we can't assign a gun object to the gun attribute. During development, if we don't know what initial value to set for the attribute when defining an attribute, at this time, We can use the keyword None on the right side of the assignment statement. In Python, the keyword None means nothing. To be precise, None is an empty object, which is a special object without any methods and attributes

First, define a Soldier class Soldier, and use the def keyword to find the initialization method__ init__ , The initialization method can simplify the creation of objects through formal parameters. The Soldier's name attribute name can be passed as a formal parameter. Recruits don't have guns, which means that we don't need guns to define a formal parameter. First define a name attribute for soldiers, self.name = name, and then define a gun attribute for soldiers, self.gun = None, because recruits don't have guns, Therefore, other gun objects cannot be used to assign values to this gun attribute, so we directly use the None keyword to define attributes without setting specific gun objects. After the two attributes are defined, the initialization method is defined

Now let's create a Soldier of more than three. Call the Soldier class to create a Soldier object called xusanduo. After the creation, use the print function to output the gun attribute of xusanduo. print(xusanduo.gun). After running, the console outputs None, which is exactly the same as the value specified in our reinitialization method (self.gun = None), xusanduo's gun is an empty object, which means xusanduo doesn't have a gun now,

class Gun:


    def __init__(self, model):
        #1. model of gun
        self.model = model

        #2. Number of bullets. Set the initial value of the number of bullets of the gun to 0
        self.bullet_count = 0

    # Define a bullet loading method. Pass in the formal parameter count to represent the bullet loading method 
    def add_bullet(self, count):

        self.bullet_count += count

    # Define how a gun fires bullets
    def shoot(self):
        # 1. Judge the number of bullets. Only when there are enough bullets can bullets be fired
        if self.bullet_count <= 0:
            print("[%s] There are no bullets..." % self.model)

            return
        # 2. Fire the bullet. After firing the bullet, let the bullet do a minus 1 operation
        self.bullet_count -= 1

        # 3. Prompt the firing information and put the gun model and the remaining bullet_count makes an output
    
        print("[%s] Protrusion...[%d]" % (self.model, self.bullet_count))


# Define a soldier class 
class Soldier:
    # Initialization methods can simplify the creation of objects by passing in formal parameters
    def __init__(self, name):
        # 1. Define the names of recruits
        self.name = name

        #2. Define the attributes of guns. Recruits do not have guns. If you do not know what initial value to set on the right side of the equal sign, you can use the keyword None to define attributes and not set specific gun objects
        self.gun = None
        # Initialization method definition complete






# After the gun class has been created, you can create a gun object in the main program

# 1. Create a gun object and create an object called ak47
ak47 = Gun("AK47")

# Load ak47 up
ak47.add_bullet(50)

# Use ak47 to fire bullets
ak47.shoot()

# 1. Create a soldier named xusanduo
xusanduo = Soldier("Xu Sanduo")

# Output the gun attribute of xusanduo object. The console outputs None, indicating that xusanduo's gun is an empty object, indicating that xusanduo does not have a gun now
print(xusanduo.gun)








Operation results:

 

You can use the assignment statement in the main program to set a gun for xusanduo, and we will give the previously created ak47 to xusanduo,   Use the assignment statement to give the ak47 to xusanduo. The console outputs the gun object and memory address. Now the soldier xusanduo has an ak47  

class Gun:


    def __init__(self, model):
        #1. model of gun
        self.model = model

        #2. Number of bullets. Set the initial value of the number of bullets of the gun to 0
        self.bullet_count = 0

    # Define a bullet loading method. Pass in the formal parameter count to represent the bullet loading method 
    def add_bullet(self, count):

        self.bullet_count += count

    # Define how a gun fires bullets
    def shoot(self):
        # 1. Judge the number of bullets. Only when there are enough bullets can bullets be fired
        if self.bullet_count <= 0:
            print("[%s] There are no bullets..." % self.model)

            return
        # 2. Fire the bullet. After firing the bullet, let the bullet do a minus 1 operation
        self.bullet_count -= 1

        # 3. Prompt the firing information and put the gun model and the remaining bullet_count makes an output
    
        print("[%s] Protrusion...[%d]" % (self.model, self.bullet_count))


# Define a soldier class 
class Soldier:
    # Initialization methods can simplify the creation of objects by passing in formal parameters
    def __init__(self, name):
        # 1. Define the names of recruits
        self.name = name

        #2. Define the attributes of guns. Recruits do not have guns. If you do not know what initial value to set on the right side of the equal sign, you can use the keyword None to define attributes and not set specific gun objects
        self.gun = None
        # Initialization method definition complete






# After the gun class has been created, you can create a gun object in the main program

# 1. Create a gun object and create an object called ak47
ak47 = Gun("AK47")

# Load ak47 up
ak47.add_bullet(50)

# Use ak47 to fire bullets
ak47.shoot()

# 1. Create a soldier named xusanduo
xusanduo = Soldier("Xu Sanduo")

# Output the gun attribute of xusanduo object. The console outputs None, indicating that xusanduo's gun is an empty object, indicating that xusanduo does not have a gun now
print(xusanduo.gun)

# Use the assignment statement and gun attribute to give ak47 to xusanduo
xusanduo.gun = ak47
# The console will output the gun object and the memory address of the object
print(xusanduo.gun)







Operation results:

If you want to modify the value of the attribute, we can use the assignment statement in the main program to set a new object for the attribute

Use the assignment statement to set a new object for the gun attribute. The gun attribute was originally an empty object None

 

4. Complete the fire method def fire()

Next, let's work together to realize the method of soldiers shooting. Take a look at the main program. First, we create a gun object, and then want the gun to load its own bullets ak47.add_bullet, want the gun to fire bullets by itself ak47.shot, but the gun can't load bullets by itself, and the gun can't fire bullets by itself. You need xusanduo to pull the trigger

Now move the cursor to the soldier class, and use the def keyword again to define a shooting method, def fire, and then move the cursor to the inside of the method. When a soldier wants to shoot, the first thing is to judge whether the soldier has a gun, and the soldier can't shoot without a gun. After the soldier has a gun, the second thing is to let the soldier shout slogans, and the third thing is, Let the gun load. The fourth thing is to fire bullets. First, judge whether the soldier's gun is an empty object. If it is equal to None, it means that the soldier has no gun. If there is no gun, use the print function to prompt and output the name of the soldier without gun. Without a gun, the second, third and fourth steps of the code do not need to be executed. Since you don't need it, just use return to return directly.

If the soldier has a gun, continue to step 2. Similarly, use the print function to output the soldier's name.

Step 3: use self.gun to find the soldier's own gun, and then use the soldier's own gun to call the method of adding bullets. Fill 50 rounds, self.gun. add_bullet.

Step 4: let the gun fire bullets, self.gun.shoot, let xusanduo call the shooting method, run the program, xusanduo shout [rush], and then [AK47] burst. After the burst, the number of bullets is reduced by 1, leaving only 49 bullets. The shooting method has been completed

Review: in the main program, we created two objects, a gun object and a soldier object, and set ak47 this object to the soldier's gun attribute. After setting, we asked the soldier to call the shooting method. There are only four sentences of code in the main program

Create gun Object > gun ("AK47")

Create Xu Sanduo > XuSanDuo = soldier ("Xu Sanduo")

Set the object ak47 to the soldier's gun attribute > xusanduo.gun = ak47

Let xusanduo call the method of shooting > xusanduo. Fire()

The most important feature of object-oriented development is to create objects and let objects call methods, and the specific implementation details of methods are encapsulated in the class

If we want to load bullets, we directly ask the gun to call the encapsulated method in the class. If we want to fire bullets, we also ask the gun to call the encapsulated method

class Gun:


    def __init__(self, model):
        #1. model of gun
        self.model = model

        #2. Number of bullets. Set the initial value of the number of bullets of the gun to 0
        self.bullet_count = 0

    # Define a bullet loading method. Pass in the formal parameter count to represent the bullet loading method 
    def add_bullet(self, count):

        self.bullet_count += count

    # Define how a gun fires bullets
    def shoot(self):
        # 1. Judge the number of bullets. Only when there are enough bullets can bullets be fired
        if self.bullet_count <= 0:
            print("[%s] There are no bullets..." % self.model)

            return
        # 2. Fire the bullet. After firing the bullet, let the bullet do a minus 1 operation
        self.bullet_count -= 1

        # 3. Prompt the firing information and put the gun model and the remaining bullet_count makes an output
    
        print("[%s] Protrusion...[%d]" % (self.model, self.bullet_count))


# Define a soldier class 
class Soldier:
    # Initialization methods can simplify the creation of objects by passing in formal parameters
    def __init__(self, name):
        # 1. Define the names of recruits
        self.name = name

        #2. Define the attributes of guns. Recruits do not have guns. If you do not know what initial value to set on the right side of the equal sign, you can use the keyword None to define attributes and not set specific gun objects
        self.gun = None
        # Initialization method definition complete

    # Define a method of shooting
    def fire(self):
        # 1. Judge whether the soldier has a gun
        if self.gun == None:
            print("[%s] No guns yet..." % self.name)

            return

        # 2. Shout slogans
        print("Go...[%s]" % self.name)


        # 3. Let the gun be loaded
        self.gun.add_bullet(50)


        # 4. Let the gun fire bullets
        self.gun.shoot()





        







# After the gun class has been created, you can create a gun object in the main program

# 1. Create a gun object and create an object called ak47
ak47 = Gun("AK47")


# 1. Create a soldier named xusanduo
xusanduo = Soldier("Xu Sanduo")



# Use the assignment statement and gun attribute to give ak47 to xusanduo
xusanduo.gun = ak47
# The soldiers fired
xusanduo.fire()
# The console will output the gun object and the memory address of the object
print(xusanduo.gun)







Operation results:

 

5. Identity operator

 

PEP 8 is the coding specification of python. It prompts us to use the if operator when comparing with None. The is operator is the identity operator in python

In python, there are two identity operators, one is and the other is not. Literally, the functions of these two identity operators are just the opposite

In python, the identity operator can be used to compare whether the memory addresses of two objects are consistent

The id function can check the memory address of a data. When using is to judge, it is actually comparing whether the memory addresses of two variables are consistent. id(x) == id(y). In terms of the reference concept we learned earlier, it is to judge whether the two variables refer to the same object

In python, data and variables are stored separately. We see the data as a small grid in memory, and then see a label for the variable. For example, there is a variable of x and a variable of Y, and then the two variables are pasted on the same small grid at the same time. In this case, we use the identity operator is to judge that x and y are equal, This is the role of the identity operator

The identity operator is used to judge whether the objects referenced by two variables are the same, while = =, is used to judge whether the values of two variables are equal

First define a list a = [1,2,3], use the id function to view the memory addresses of the following table a, and then define a list b = [1,2], use the id function to view the memory addresses of the following table b. now the contents and memory addresses of lists a and b are different. Now add a data 3 to list b so that b = [1,2,3], and then use = = to compare the two variables. After entering, the return is True, which means that the contents of lists a and b are exactly the same

 

If the identity operator is used, False is returned because the memory addresses of lists a and b are different, which is the difference between is and = =

 

When comparing None, None is an empty object. It is recommended to use is instead of, etc. of course, if = =, there will be no problem with the execution effect of the program, because they are empty lists and have no content. It is only recommended to use is to judge according to the coding specification of PEP 8

class Gun:


    def __init__(self, model):
        #1. model of gun
        self.model = model

        #2. Number of bullets. Set the initial value of the number of bullets of the gun to 0
        self.bullet_count = 0

    # Define a bullet loading method. Pass in the formal parameter count to represent the bullet loading method 
    def add_bullet(self, count):

        self.bullet_count += count

    # Define how a gun fires bullets
    def shoot(self):
        # 1. Judge the number of bullets. Only when there are enough bullets can bullets be fired
        if self.bullet_count <= 0:
            print("[%s] There are no bullets..." % self.model)

            return
        # 2. Fire the bullet. After firing the bullet, let the bullet do a minus 1 operation
        self.bullet_count -= 1

        # 3. Prompt the firing information and put the gun model and the remaining bullet_count makes an output
    
        print("[%s] Protrusion...[%d]" % (self.model, self.bullet_count))


# Define a soldier class 
class Soldier:
    # Initialization methods can simplify the creation of objects by passing in formal parameters
    def __init__(self, name):
        # 1. Define the names of recruits
        self.name = name

        #2. Define the attributes of guns. Recruits do not have guns. If you do not know what initial value to set on the right side of the equal sign, you can use the keyword None to define attributes and not set specific gun objects
        self.gun = None
        # Initialization method definition complete

    # Define a method of shooting
    def fire(self):
        # 1. Judge whether the soldier has a gun
        if self.gun is None:
            print("[%s] No guns yet..." % self.name)

            return

        # 2. Shout slogans
        print("Go...[%s]" % self.name)


        # 3. Let the gun be loaded
        self.gun.add_bullet(50)


        # 4. Let the gun fire bullets
        self.gun.shoot()





        







# After the gun class has been created, you can create a gun object in the main program

# 1. Create a gun object and create an object called ak47
ak47 = Gun("AK47")


# 1. Create a soldier named xusanduo
xusanduo = Soldier("Xu Sanduo")



# Use the assignment statement and gun attribute to give ak47 to xusanduo
xusanduo.gun = ak47
# The soldiers fired
xusanduo.fire()
# The console will output the gun object and the memory address of the object
print(xusanduo.gun)







 

Keywords: Python

Added by silrayn on Sat, 04 Sep 2021 23:34:16 +0300