10 days of playing with Python Day 7: Python object-oriented comprehensive explanation and code examples

Today's content

  • Encapsulation (the process of defining a class)

    • Case (storage furniture)
  • inherit

  • Polymorphism

  • Packaging supplement

    • Private and public permissions
    • Classification of attributes (instance attributes, class attributes)
    • Classification of methods (instance methods, class methods, static methods)

Package case

 
 

 
 
# Define furniture class
class HouseItem:
    """Furniture"""
    def __init__(self, name, area):
        """Method of adding attributes"""
        self.name = name
        self.area = area
    def __str__(self):
        Return f'Furniture name {self.name}, floor area {self.area} square meters'
class House:
    """House category"""
    def __init__(self, name, area):
        self.name = name # House type
        self.total_area = area #Total area
        Self.free_area = area #Remaining area
        ​ ​ ​ self.item_list = [] ​ # Furniture name list
    def __str__(self):
        Return f"House type: {self.name}, total area: {self.total_area} square meters, remaining area: {self.free_area} square meters, " \
               F & quot; furniture name list: {self.item_list} & quot;
    def add_item(self, item): # The object of furniture represented by item
        # Determine the relationship between the remaining area of ​​the house (self.free_area) and the floor area of ​​the furniture (item.area)
        ​​ # The house object represented by self is missing a furniture object and can be solved by passing parameters.
        if self.free_area > item.area:
            ​ ​ ​ ​ # Add furniture, ---> Add data to the list
            self.item_list.append(item.name)
            # Modify the remaining area
            self.free_area -= item.area
            print(f'{item.name} added successfully')
        else:
            Print('The remaining area is not enough, let’s get a bigger house')
#Create furniture objects
bed = HouseItem('Simmons', 4)
chest = HouseItem('wardrobe', 2)
table = HouseItem('dining table', 1.5)
print(bed)
print(chest)
print(table)
#Create a house object
house = House('Three bedrooms and one living room', 150)
print(house)
# add bed
house.add_item(bed)
print(house)

Case 2

 
 

 
 
Requirements: A certain web project login page contains: user name, password, verification code, login button and login method
Write code to implement the above functions. Use print output in the login method.
Class name: LoginPage
Attributes: username, password, verification code, login button
Method: login __init__
 
 

 
 
class LoginPage:
    def __init__(self, username, password, code):
        self.username = username
        self.password = password
        self.code = code
        self.btn = 'Login'
    def login(self):
        Print(f'1. Enter username {self.username}')
        Print(f'2. Enter password {self.password}')
        Print(f'3. Enter verification code {self.code}')
        Print(f"4. Click button {self.btn}")
login = LoginPage('admin', '123456', '8888')
login.login()

private and public

 
 

 
 
1. For methods and attributes defined in Python, access control permissions can be added (that is, where can this attribute and method be used)
2. Access control permissions are divided into two types, public permissions and private permissions
3. Public permissions
    > Directly written methods and properties are all public
    > Public methods and properties can be accessed and used anywhere
4. Private permissions
    > Inside the class, add two underscores in front of the attribute name or method name, and the attribute or method becomes private.
    > Private methods and properties can only be used within the current class
5. When to define private
    > 1. If you don’t want a certain attribute or method to be accessed and used outside the class, just define it as private.
    > 2. In testing, it is generally not used very much, just make it public.
    > 3. During development, what is considered private will be determined based on the requirements document.
6. If you want to operate private properties outside the class, the method is to define a public method inside the class, and we operate through this public method.
# Replenish:
#Object.__dict__ Magic attribute, you can return the attributes of the object into a dictionary
  • Case

     

     
    Define a Person class with attributes name, age (private)
  • code

     

     
    class Person:
        def __init__(self, name, age):
            self.name = name # Name
            ​ ​ # The essence of privateness is that when the Python interpreter executes the code and finds that there are two _ in front of the attribute name or method name, it will rename the name
            # Will add _class name prefix in front of this name, that is, self.__age ===> self._Person__age
            Self.__age = age # Age, define it as a private attribute, add two _ in front of the attribute name
        def __str__(self): # Private attributes can be accessed within the class
            Return f'Name: {self.name}, Age: {self.__age}'
    xm = Person('Xiao Ming', 18)
    print(xm)
    # Directly access the age attribute outside the class
    # print(xm.__age) # An error will be reported. Private attributes cannot be used directly outside the class.
    # Directly modify the age attribute
    xm.__age = 20 # This is not modifying a private attribute, but adding a public attribute __age
    print(xm) # Name: Xiao Ming, Age: 18
    print(xm._Person__age) # Can be used but don’t use 18
    xm._Person__age = 19
    print(xm) # Name: Xiao Ming, Age: 19

inherit

 
 

 
 
1. Inheritance describes the relationship between classes
2. Benefits of inheritance: Reduce code redundancy (the same code does not need to be written multiple times) and can be used directly

grammar

 
 

 
 
# class A(object):
class A: # There is no parent class, but there is a parent class. Object, the object class is the top-level (original) class in Python
    pass
class B(A): # Class B, inherits from class A
    pass 
 
 

 
 
the term:
1. Class A, called the parent class (base class)
2. Class B is called a subclass (derived class)
Single inheritance: A class inherits only one parent class, which is called single inheritance.
Features after inheritance:
    > After the subclass (B) inherits the parent class (A), the objects of the subclass can directly use the public properties and methods defined in the parent class
  • Case

     

     
    1. Define an animal class, eat
    2. Define a dog class, inherit from animal class, eat and bark
    3. Define a Roaring Dog class, inherit from Dog class
  • code

     

     
    # 1. Define an animal class, eat
    class Animal:
        def eat(self):
            Print('Want to eat')
    # 2. Define a dog class, inherit from animal class, eat, bark
    class Dog(Animal):
        def bark(self):
            Print('Woof woof woof....')
    # 3. Define a Roaring Dog class, inherit from Dog class
    class XTQ(Dog):
        pass
    #Create an animal class object
    # ani = Animal()
    # ani.eat()
    #Create dog object
    # dog = Dog()
    # dog.eat() # Call the method in the parent class
    # dog.bark() # Call the method in your own class
    #Create Xiaotian dog object
    xtq = XTQ()
    xtq.bark() # Call the method of the parent Dog class
    xtq.eat() # You can call methods in the parent class of the parent class
  • in conclusion

     

     
    Object.method() calling method in python
    1. Now look for this method in your own class. If so, call it directly.
    2. If there is no search in the parent class, if there is, call it directly
    3. If not, search in the parent class of the parent class. If there is one, call it directly.
    4 ...
    5. If there is one in the object class, call it directly. If not, the code will report an error.

rewrite

 
 

 
 
Rewriting: A method with the same name as in the parent class is defined in the subclass, which is rewriting.
Reason for rewriting: The method in the parent class cannot meet the needs of the subclass object, so it is rewritten
Features after rewriting: Call the subclass byte method, no longer call the parent class method
How to rewrite:
    >1. Override (completely abandon the functions in the parent class, do not rewrite them)
    >2. Extension (the functions in the parent class are still called, but some new functions are added) (used more)
cover
 
 

 
 
1. Directly define a method in the subclass with the same name as in the parent class
2. Write new code directly in the method
 
 

 
 
class Dog:
    def bark(self):
        Print('Woofing woofing...')
class XTQ(Dog):
    # The XTQ bark method is no longer barking, but is instead barking.
    def bark(self):
        print
xtq = XTQ()
xtq.bark()
Extend functionality in parent class
 
 

 
 
1. Directly define a method in the subclass with the same name as in the parent class
2. Call the method super().method() in the parent class at the appropriate place
3. Write new features added
 
 

 
 
class Dog:
    def bark(self):
        Print('Woofing woofing...')
        Print('Woofing woofing...')
class XTQ(Dog):
    # The bark method of XTQ class is no longer barking, it is changed to
    # 1. First, howl and howl (new function) 2, howl and howl (function in parent class) 3. howl and howl (new function)
    def bark(self):
        print
        ​ ​ #Call the code in the parent class
        Super().bark() # print() What if there are multiple lines of code in the parent class?
        print
xtq = XTQ()
xtq.bark()

polymorphism [understand]

 
 

 
 
1. It is a technique for writing code and calling
2. The same method, passing in different objects, gets different results when executed. This phenomenon is called polymorphism.
3. Polymorphism can increase the flexibility of code
--------
Which object calls a method, just look for the method in your own class. If you can't find it, look for it in the parent class.

Properties and methods

 
 

 
 
Everything in Python is an object.
Even a class defined using class is also an object

Division of objects

instance object (instance)
 
 

 
 
1. Objects created through classname() are called instance objects, or instances for short.
2. The process of creating an object is called instantiation of a class
3. The objects we usually refer to refer to instance objects (instances)
4. Each instance object has its own memory space and stores its own attributes (instance attributes) in its own memory space.
class object(class)
 
 

 
 
1. A class object is a class, or it can be thought of as a class name
2. Class objects are created by the Python interpreter during code execution.
3. The role of the class object: ① Use the class object to create an instance class name (), ② The class object also has its own memory space, which can save some attribute value information (class attributes)
4. In a code, a class has only one memory space

Division of attributes

Instance properties
  • Concept: It is an attribute that an instance object has

  • Definition and use

     

     
    In the init method, use self.attribute name = attribute value to define
    In the method, use self.property name to get (call)
  • Memory

     

     
    Instance attributes, a copy exists in each instance
  • When to use

     

     
    1. Basically 99% of them are instance attributes, which are defined through self
    2. Find multiple objects to determine whether the values ​​are the same. If they are all the same and change at the same time, it is generally defined as a class attribute, otherwise it is defined as an instance attribute.

class attributes
  • Concept: It is a property that a class object has

  • Definition and use

     

     
    Within a class and outside a method, directly defined variables are class attributes.
    Usage: class object.property name = property value or class name.property name = property value
    Class object.Attribute name or Class name.Attribute name
  • Memory

     

     
    Only one copy of the class object exists

Division of methods

 
 

 
 
Methods, functions defined in a class using the def keyword are methods
Instance methods (most commonly used)
  • definition

     

     
    # Methods defined directly in a class are instance methods
    class Demo:
        def func(self): # The parameter is generally written as self, which represents the instance object
            pass
  • Define timing (when to use it)

     

     
    If you need to use instance attributes in a method (that is, you need to use self), then this method must be defined as an instance method
  • transfer

     

     
    Object.Method name() # No need to pass parameters to self
Class method (know how to use it)
  • definition

     

     
    # Write the @classmethod decorator above the method name (method decorated with @classmethod)
    class Demo:
        @classmethod
        def func(cls): # The parameter is generally written as cls, which represents the class object (i.e. class name) class
            pass 
  • Define timing (when to use it)

     

     
    1. Premise, there is no need to use instance attributes (ie self) in the method
    2. Using class attributes, this method can be defined as a class method (it can also be defined as an instance method)
  • transfer

     

     
    # 1. Called through class object
    Class name.Method name () # There is no need to pass parameters to cls, the python interpreter will automatically pass them
    # 2. Called through instance object
    Instance.Method name() # There is no need to pass parameters to cls, the python interpreter will automatically pass them
Static methods (basically not used)
  • definition

     

     
    # Write the @staticmethod decorator above the method name (method decorated with @staticmethod)
    class Demo:
        @staticmethod
        def func(): # Generally no parameters
            pass
  • Define timing (when to use it)

     

     
    1. Premise, there is no need to use instance attributes (ie self) in the method
    2. Instead of using class attributes, this method can be defined as a static method
  • transfer

     

     
    # 1. Called through class object
    Class name.Method name()
    # 2. Called through instance object
    instance.methodname()  

practise

Exercise 1
 
 

 
 
Define a Dog class and define a class attribute count to record the number of objects of this class created. (That is, every time an object is created, the value of count will be increased by 1) Instance attribute name
 
 

 
 
class Dog:
    # Define class attributes
    count = 0
    #Define instance attributes, in init method
    def __init__(self, name):
        Self.Name = name # instance attribute
        ​ ​ # Because every time an object is created, the init method will be called, so the operation of adding 1 to the number is written in the init method.
        Dog.count += 1
# Outside the class
#Print output how many objects have been created so far
print(Dog.count)  # 0
# Create an object
dog1 = Dog('小花')
#Print output how many objects have been created so far
print(Dog.count)  # 1
dog2 = Dog # It is not a created object, the number remains unchanged
dog3 = dog1 # It is not a created object, the number remains unchanged
print(Dog.count)  # 1
dog4 = Dog('大黄') #Create an object, number + 1
print(Dog.count)  # 2
dog5 = Dog('小白')
print(Dog.count)  # 3
# Supplement, you can use instance object.class attribute name to get the value of the class attribute (the reason is, the search order of instance object attributes, first search in the instance attributes, and use it directly if you find it
#If it is not found, it will be searched in the class attributes. If it is found, it can be used. If it is not found, an error will be reported)
print(dog1.count)  # 3
print(dog4.count)  # 3
print(dog5.count)  # 3

Question 2

Define a game class Game, including instance attributes player name (name)

  1. Requires recording the highest score of the game (top_score class attribute),

  2. Definition method: show_help Display the game's help information output这是游戏的帮助信息

  3. Definition method: show_top_score, print out the highest score of the game

  4. Definition method: start_game, start the game, the rules are as follows

    1. Use random numbers to get the score range of this game(10 - 100 )之间

    2. Determine the relationship between this score and the highest score

      • If this score is higher than the highest score,

        • Modify high score
      • If the score is less than or equal to the highest score, no operation will be performed

    3. Output the score of this game

  1. Main program steps

     

     
    # 1) Create a Game object Xiao Wang
    # 2) Xiao Wang plays the game once,
    # 3) Check historical high scores
    # 4) Xiao Wang plays the game again
    # 5) View all-time high scores
    # 6) View the game’s help information

  • basic version

     

     
    import random
    class Game:
        # Class attribute, the highest score of the game
        top_score = 0
        def __init__(self, name):
            ​ ​ #Define instance attribute name
            self.name = name
        def show_help(self):
            Print('This is the help information for the game')
        def show_top_score(self):
            print(f'The highest score of the game {Game.top_score}')
        def start_game(self):
            Print(f'{self.name} starts a game, during the game...,', end='')
            score = random.randint(10, 100) # The score of this game
            Print(f'The score of this game is {score}')
            if score > Game.top_score:
                # Modify the highest score
                Game.top_score = score
    xw = Game('小王')
    xw.start_game()
    xw.show_top_score()
    xw.start_game()
    xw.show_top_score()
    xw.show_help()
  • Optimization (using class methods and static methods)

     

     
        @staticmethod
        def show_help():
            Print('This is the help information for the game')
        @classmethod
        def show_top_score(cls):
            Print(f'The highest score of the game {cls.top_score}')

Guess you like

Origin blog.csdn.net/shenchengyv/article/details/135037548