[object oriented in Python]

Object oriented in Python

Object oriented programming is one of the most effective programming methods. Object oriented programming is also supported in C + + and Java, JavaScript and other programming languages. Of course, python is no exception.

class

Class is the "template" for creating objects. When writing a class, you can define the common behavior of a large class of objects. When you create objects based on classes, each object automatically has this common behavior, and then you can give each object a unique personality as needed.

  • Instantiation: create objects based on classes

Create class

python2.x and python 3 The process of creating classes in X is slightly different. The following is mainly based on Python 3 The grammar of X is dominant

  • Keyword: class is used to define a class
  • The first letter of a class name is usually capitalized
  • __ init__(self): it is a constructor. The first parameter must be self, and the following parameters are the parameters passed in when instantiating the class
  • When defining a class, if no parameters are passed in, you can not define a constructor
class Car():
    def __init__(self,name,color,brand):
        # Define object properties (also known as variables)
        self.name = name # Get the value stored in the formal parameter name and store it in the variable name, and then the variable is associated with the currently created instance
        self.color = color
        self.brand = brand

    def kind(self):
        #The object attributes defined in class methods can be used in methods in the same class, but they can only be used in another class method after they have been initialized in the class method
        self.level = "A great car" 
        size = "large"  # This is the variable of the class method
        print(self.name+"The vehicle type is::"+self.type)

    def drive(self):
        print(self.name+"Driving a car"+self.color+self.type)

    def evaluate(self):
        print(self.level)
  • self is a reference to the instance itself, which enables the instance to access the properties and functions (Methods) in the class.
  • Each function (method) call associated with a class automatically passes the argument self
  • When defining a class function (method), you must use self as a formal parameter, which is also the main difference between ordinary methods and class methods
  • Class methods only need to pass in a self as an argument, which can arbitrarily use the properties in the class and call the methods in the class

Use class

  • Create objects with classes: object name = class name ()
  • Access object properties: object name attribute
  • Use object method: object name Method ()
# Create an instance using the Car class
car1 = Car("Zhang San","Pink","Benz") # Create an object
# The parameters passed in can be specified. If not specified, the parameters must be passed in order
car2 = Car(name = "Li Si",brand="bmw",color="black") # This transfer of parameters does not need to be in order
print(car1.color) # Use object properties
car1.kind() # Method of calling object
car1.drive() # Call the method of the object 
  • modify attribute
    • It can be directly through the object Property to modify the assignment
    • You can also pass attribute values into methods by defining class methods
    • Change the property value by calling a method
class Car():
    def __init__(self,name,color,brand):
        self.name = name
        self.color = color
        self.brand = brand
        self.capacity = 5 # Number of seats, default initial value
        self.num = 0
        self.introduce = "Car introduction"

    def update_capacity(self,capacity):
        self.capacity = capacity

    def update_num(self):
        self.num += 1
        
    def getNum(self):
        print("num:%d"%self.num)

    def getCapacity(self):
        print("capacity:%d"%self.capacity)

    def getIntroduce(self):
        print("introduce:%s"%self.introduce)

    def printGet(self):
        self.getNum()
        self.getCapacity()
        self.getIntroduce()

xiaoming_car = Car("Xiao Ming","green","Honda")
xiaoming_car.printGet()
print("Modified attribute value")

# The first is to modify the attribute value directly
xiaoming_car.introduce = "This is an awesome car"
# The second method is to pass parameters through class methods
xiaoming_car.update_capacity(3)
# The third method: modify through class method
xiaoming_car.update_num()

xiaoming_car.printGet()

Output:

num:0
capacity:5
introduce:Car introduction
 Modified attribute value
num:1
capacity:3
introduce:This is an awesome car

Proprietary class

Proprietary methodexplain
__init__Constructor, called when the object is generated
__del__Destructor, used when releasing an object
__repr__Print, convert
__setitem__Assignment by index
__getitem__Get value by index
__len__Get length
__cmp__Comparison operation
__call__function call
__add__Addition operation
__sub__Subtraction operation
__mul__Multiplication operation
__truediv__Division operation
__mod__Remainder operation
__pow__Power

inherit

Inheritance is a new class created on the basis of existing classes. This new class "inherits" the properties and methods of existing classes, and can customize things belonging to new classes on this basis. The inherited class is the parent class, and the new class is the subclass. The subclass inherits all the properties and methods of its parent class, and can also define its own properties and methods.

  • Class class name (inherited class), that is, the inherited parent class, is written in parentheses after the definition class
  • python can inherit multiple classes. If there are multiple parent classes, separate them with,

Construction method of subclass

  • When creating an instance of a subclass, Python first needs to complete the task of assigning values to all properties of the parent class. To this end, subclass methods__ init__ () need help from parent class

  • super() is a special function (method) that associates a parent class with a child class. The parent class is also called super class, so super() is used to connect the construction methods of parent class and child class

    • super().__init__ (), which must be placed in the constructor of the subclass, i.e__ init__ () in function
  • Take a chestnut

class Game():
    # The default parameter should follow the non default parameter, otherwise an error will be reported
    #For example: name and price = 0.00, name must be put in front, and price with default parameter must be put behind
    def __init__(self,name,type="Mobile Games",price=0.00):
        self.name = name
        self.type = type
        self.price = price

class Shop():
    def action(self):
        # print("Welcome to{}Game store!".format(self.name)) # self.name uses the attribute of the subclass, but because the parent class does not declare the attribute, if you directly instantiate the parent class and call this method again, an error will be reported
        print("Welcome to the game store!")
        
        
class Shooter(Game,Shop):  # Inherit multiple parent classes
    def __init__(self,name,size,type="Mobile Games",price=0.00):
        # Using super() means putting the attributes in the constructor under the parent class into the child class, so that the child class can inherit the attributes of the parent class
        super().__init__(name,type,price)
        # Equivalent to the following writing
        # self.name = name
        # self.type = type
        # self.price = price
        self.size = size  #The added subclass attribute takes effect only in subclasses

Override the method of the parent class

  • For the method of the parent class, if its method is not applicable to the subclass, it can be overridden in the subclass
  • Rewriting is to redefine the method name of the parent class. When the method name of the child class is the same as that of the parent class, the interpreter will call the content of the child class method first, so as to ignore the content of the parent class method
class Game():
    # The default parameter should follow the non default parameter, otherwise an error will be reported
    #For example: name and price = 0.00, name must be put in front, and price with default parameter must be put behind
    def __init__(self,name,type="Mobile Games",price=0.00):
        self.name = name
        self.type = type
        self.price = price

class Shop():
    def action(self):
        print("Welcome to the game store!")

class Shooter(Game,Shop):  # Inherit multiple parent classes
    def __init__(self,name,size,type="Mobile Games",price=0.00):
        # Using super() means putting the attributes in the constructor under the parent class into the child class, so that the child class can inherit the attributes of the parent class
        super().__init__(name,type,price)
        self.size = size

    def action(self):  # Override the method of the parent class Shop
        print("Welcome to{}Game store!".format(self.name))

Use instances as properties

As more and more details are added to the class: the attribute and method lists and files are getting longer and longer. In this case, you may need to extract a part of the class as a separate class. You can split a large class into several small classes that work together, and then instantiate the small class in one class and use the instance as an attribute.

  • The instantiation of another class is implemented in the class, that is, the instance of another class is taken as an attribute of the class
  • The advantage of this is that large classes can be divided into multiple small classes working together, and a huge class can be reduced (referring to the number of lines of code), which is convenient for subsequent development and sorting
class Game():
    # The default parameter should follow the non default parameter, otherwise an error will be reported
    #For example: name and price = 0.00, name must be put in front, and price with default parameter must be put behind
    def __init__(self,name,type="Mobile Games",price=0.00):
        self.name = name
        self.type = type
        self.price = price

    def getName(self):
        print("This is a%s game"%self.name)

    def getCost(self):
        print("Cost of the game%d"%self.price)

    def setPrice(self,set_price):
        self.price = set_price

    def promotePrice(self,cost):
        self.price += cost

    def getType(self):
        print("What is the type of game%s"%self.type)


class Shop():
    def action(self):
        # print("Welcome to{}Game store!".format(self.name)) # self.name uses the attribute of the subclass, but because the parent class does not declare the attribute, if you directly instantiate the parent class and call this method again, an error will be reported
        print("Welcome to the game store!")

class Skill():
    def __init__(self,arm,energy):
        self.arm = arm
        self.energy = energy
    def attack(self):
        print("Weapon for%s"%self.arm)

class Shooter(Game,Shop):  # Inherit multiple parent classes
    def __init__(self,name,size,type="Mobile Games",price=0.00):
        # Using super() means putting the attributes in the constructor under the parent class into the child class, so that the child class can inherit the attributes of the parent class

        super().__init__(name,type,price)
        # self.name = name
        # self.type = type
        # self.price = price
        self.size = size
        self.skill = Skill("m416",500) # The instantiation of another class is implemented in the class, that is, the instance of another class is taken as an attribute of the class

    def action(self):
        print("Welcome to{}Game store!".format(self.name))

# Class instantiation
# Note: if the incoming parameters are specified, they may not be written in sequence, but they must all be written as formal parameters with the specified name for transmission
# This is wrong game1 = Shooter(size="100GB", Jedi survival "," end game ")
# If the parameter is not passed, the default value is taken
game1 = Shooter(size="100GB",name="Jedi survival",type="End swim")
game2 = Shooter("Game for Peace","5GB","Mobile Games")
game2.skill.attack()

Import class

When new functions are added to the class, the file will gradually become huge, which is not conducive to maintenance and neat code, which is contrary to the original concise concept of Python. Python strictly uses indentation to standardize the code logic in order to be concise and neat; Therefore, python allows classes to be stored in modules, and then the required modules can be imported into the main program. The advantage of this is to make the code as concise as possible.

  • A module is a py file
  • You can write a class into a module
  • There can be multiple classes in a module, so the file name of the module does not need to be capitalized

Import a single class

  • Import using the import keyword

  • If you import a class from a module, use the from module name to import the class name

  • as keyword can assign an alias to a module / class / function

    • If the name of the module / class / function to be imported may conflict with the existing name in the program, or the name of the function is too long, you can specify a short and unique alias - another name of the module / class / function, similar to a nickname.
    • To specify this special nickname, you only need to use the as keyword after importing it: import module / class / function name as alias or from module name import class / function name as alias
  • For example, from supermarket import GetMessage as gm imports the GetMessage class from the supermarket module and changes the class name to gm

p.s. importing a specific method (function) from a module also uses the import keyword, that is, from module name import function name

Import multiple classes from a module

Although there should be some correlation between classes in the same module, any number of classes can be stored in a module as needed, that is, there can be any number of classes in a module

  • Any number of classes can be imported into the program file as needed

  • The import method is the same as importing a single class, with the import keyword and separated by

  • For example: import from supermarket, import commerce, GetMessage and pay

  • Import all classes in the module: from module name import*

    • This method of importing is not recommended
      1. When there are many class names, you will not know which classes your program uses
      2. It is possible to import a class with the same name as other things in the program file, causing an undetectable error
  • You can also import the whole module directly with the import module name

    • When you need to import many classes from one module, it is best to import the whole module

    • Use module name Class name to access the class

      It can avoid name conflicts that may be caused by each class in the import module. This is different from all modules of the imported class. Even if the class name is the same, the way to import the whole module is through the module name If the class name is used to access the class, there will be no naming conflict, and the way to import all classes can only be accessed by the class name, which is easy to conflict.

      For example: suppose there is a fruit Py file, there are multiple classes, among which you want to access the Apple class

      # Import the whole fruit module
      import fruit
      a = fruit.Apple()
      
      # Import all classes in the fruit module
      from fruit import *
      a = Apple()
      

Importing one module into another

Sometimes, you need to spread classes into multiple modules to avoid modules being too large or storing irrelevant classes in the same module.

When storing classes in multiple modules, you may find that classes in one module depend on classes in another module.

In this case, you can import the necessary classes in the previous module.

  • When a class in a module has a dependent class in another module, you need to import the dependent class from another module into this module
  • Finally, import the class of the module into the main program

Tips :

  1. The class name shall adopt hump naming method, that is, the first letter of each word in the class name shall be capitalized without underline. The instance name and module name are in lowercase and underlined between words.

  2. You can use blank lines to organize your code, but don't abuse it. In a class, you can use an empty line to separate methods; In a module, you can use two empty lines to separate classes.

  3. When you need to import the modules in the standard library and the modules you write at the same time, first write the import statement to import the modules in the standard library, then add a blank line, and then write the import statement to import the modules you write. In programs with multiple import statements, this makes it easier to understand where the modules used by the program come from.

Take a big chestnut:

Imitate supermarket shopping, add goods to the shopping cart, and then check out.

supermarket.py file

# Commodity category
class Commodity():
    def __init__(self,name,price=0.00):
        #Define the attributes of the class, commodity name, commodity price and commodity discount
        self.goodsName = name
        self.price = price
        self.discount=1.00

    def setGoodsName(self,name):
        self.goodsName = name
        print("The item has been named:{}",format(self.goodsName))

    def setPrice(self,price):
        self.price = price
        print("The price of this item has been set to:{:.2f}element".format(self.price))

    def setDiscount(self,discount):
        self.discount = discount
        print("The discount for this item is{:.2f}".format(self.discount))

# Check out
class Pay():
    def __init__(self):
        self.count = 0.00
        self.dic = {}  # A list of commodity names. key is the commodity name and num is the quantity

    def add(self,name,count, num=1): # Add item
        # self.dic.__setitem__(name,num) #Set the key and value of the dictionary
        if num < 1:
            return False
        count = float(count)
        self.dic.setdefault(name, num) #Set the key and value of the dictionary
        now_count = count*num
        self.count += now_count
        print("The item name added to the shopping cart is:{} The amount added is:{:.2f}".format(name,now_count))

    def sub(self,name,count,num=1):  # Delete item
        if num < 1:
            return False
        now_count = count*num
        self.count -= now_count
        self.dic.pop(name)
        print("The name of the shopping cart is deleted:{} The amount to be deducted is:{:.2f}".format(name, now_count))

    def balance(self):  # Check out
        print("bill : ")
        print("Trade name\t quantity\t")
        for items in self.dic.items():
            print("{}\t{}\t".format(items[0],items[1]))

        print("The total amount to be paid is:{:.2f}element".format(self.count))

message.py file

from supermarket import Commodity
# The classes in the current module depend on the Commodity class in the supermarket module

# Get commodity information class
class GetMessage(Commodity):
    def __init__(self,name,price=0.00):
        super().__init__(name,price) # Correlates the properties in the constructor of the parent class with each other

    def getName(self):
        try:
            # print("the name of the product is: {}". format(self.goodsName))
            return self.goodsName
        except:
            print("The product is not named")

    def getPrice(self):
        try:
            # print("the price of this commodity is {:. 2f}. format(self.price))
            return self.price
        except:
            print("No price has been set for this item")

    def getDiscount(self):
        # if self.discount == 1.00:
        #     print("this item is not discounted")
        # else:
        #     print("the discount of this product is {:. 2f}".format(self.discount))
        return self.discount

shopping.py

from message import GetMessage as gm
from supermarket import Commodity, Pay

# Add product information
def goods():
    apple = gm("Apple", 2)
    orange = gm("orange", 3)
    banana = gm("Banana", 1.5)
    return [apple,orange,banana]



def goodsMessage(ls):
    print("Output product information:")
    print("Trade name\t commodity price\t Commodity discount\t")
    for item in ls:
        print("{}\t{}\t\t{}\t".format(item.getName(),item.getPrice(),item.getDiscount()))

    print("Corresponding list index:")
    num = 0
    for item in ls:
        print("{}\t{}".format(num,item.getName()))
        num+=1

def buy(ls):
    sum = Pay()
    # sum.add(banana.goodsName, banana.price, 3)
    while True:
        a = input("Please enter the index you want to add to the shopping cart:(input q Exit checkout)")
        if a == 'q':
            break
        try:
            num = int(a)
            b = int(input("Please enter the quantity to purchase:"))
            sum.add(ls[num].getName(), ls[num].getPrice(), b)
        except:
            print("Incorrect input,Please re-enter")
            continue
    # Final checkout
    sum.balance()

if __name__ == '__main__':
    ls =goods()
    goodsMessage(ls)
    buy(ls)

tips: from shopping When the PY file starts running, the three py files should be placed in the same folder, so that the system can successfully find the path of the module

Operation effect:

Output product information:
Trade name	commodity price	Commodity discount	
Apple    	2		1.0	
orange 	3		1.0	
Banana 	1.5		1.0	
Corresponding list index:
0	Apple
1	orange
2	Banana
 Please enter the index you want to add to the shopping cart:(input q Exit checkout)0
 Please enter the quantity to purchase:2
 The item name added to the shopping cart is:Apple added an amount of:4.00
 Please enter the index you want to add to the shopping cart:(input q Exit checkout)1
 Please enter the quantity to purchase:3
 The item name added to the shopping cart is:The amount of oranges added is:9.00
 Please enter the index you want to add to the shopping cart:(input q Exit checkout)q
 bill : 
Trade name	quantity	
Apple	    2	
orange 	3	
The total amount to be paid is:13.00 element

reference material:

   Python Programming: from introduction to practice [US] Eric Matthes translator: Yuan Guozhong

Tags: Python OOP

Posted by stickynote427 on Sat, 16 Apr 2022 00:21:07 +0930