Hello, students. This chapter will share with you some methods of object-oriented programming, and take you to master object-oriented programming from simple to deep through some cases.
1. Basic class instantiation
The method of creating a class is the class variable name:, the instantiation method is the class name (), and the method of allocating attributes is the instance name Attribute name = value
#(1) Create class class Item: # The method to create a class is the class name: pass # Do nothing #(2) Instantiation item1 = Item() # Create the instantiated object item1 of the item class #(3) Assign attributes to instantiated objects item1.name = 'phone' item1.price = 100 item1.quantity = 5 #(4) Print results print(type(item1)) # <class '__main__.Item'> print(type(item1.name)) # <class 'str'> print(type(item1.price)) # <class 'int'> print(type(item1.quantity)) # <class 'int'>
2. Create method in class
The functions defined inside the class are called methods, which can be applied to all class instantiated objects. The first parameter of the function defined inside the class is self by default, which represents the instantiated object of the class. In the following code, it refers to item1. Call the method defined inside the class outside the class: object name Method name (parameter)
#(1) Define class class Item: # The method to create a class is the class name: #(2) Create method in class # When this method is called, the object itself is passed as the first parameter, self def calculate_total_price(self, x, y): return x * y # Return product #(3) Instantiation item1 = Item() # Create the instantiated object item1 of the item class #(4) Assign attributes to instantiated objects item1.name = 'phone' item1.price = 100 item1.quantity = 5 #(5) Call the method, self stands for item1, pass in two parameters, x stands for price, y stands for quantity, res = item1.calculate_total_price(item1.price, item1.quantity) print(res) # 500 # Instantiate another item2 = Item() # Create the instantiated object item1 of the item class item2.name = 'MacBook' item2.price = 1000 item2.quantity = 3 print(item2.calculate_total_price(item2.price, item2.quantity)) # Output 3000
3. Class initialization
3.1 no default value for initialization
After class instantiation, you need to assign attributes to each object separately, as shown in step (4) of the previous section. If there are many objects, it will greatly increase the workload. Therefore, we hope that when a class instantiates an object, it can automatically assign attributes to the object. Initialization method: define def in the class__ init__ (self, parameter): when the class is instantiated, all contents in the initialization function will be automatically executed and the attribute allocation will be completed automatically.
#(1) Define class class Item: # Create a class #(2) Initialization. When this class is instantiated, the init content will be executed automatically def __init__(self, name, price, quantity): # Dynamic attribute assignment self.name = name # Assign a value to the instantiation attribute, which is equivalent to Item1 name = 'phone' self.price = price # Equivalent to Item1 price = 100 self.quantity = quantity # Equivalent to Item2 quantity = 3 #(3) Instantiate to create the instantiated object item1 of the item class # The contents in the initialization are automatically executed, and do not need to be defined one by one item1 = Item('Phone', 100, 5) item2 = Item('MacBook', 1000, 3) # Print results print('name1:', item1.name, 'price1:', item1.price, 'quantity1:', item1.quantity) print('name2:', item2.name, 'price2:', item2.price, 'quantity2:', item2.quantity) # name1: Phone price1: 100 quantity1: 5 # name2: MacBook price2: 1000 quantity2: 3
3.2 initialization has default values
During initialization, you can set default values for properties. In that case, when instantiating, if the value of a property is not given, the property is given a default value. For example, during initialization, the default values of price and quantity have been given, so item1 directly uses the default values of these two attributes, and item2 changes the default values of these two attributes.
#(1) Create class class Item: # Create a class #(2) Initialization. When this class is instantiated, the init content will be executed automatically # There are default values for price and quantity, so you don't need to transfer values def __init__(self, name, price=50, quantity=10): # Dynamic attribute assignment self.name = name # Assign a value to the instantiation attribute, which is equivalent to Item1 name = 'phone' self.price = price # Equivalent to Item1 price = 100 self.quantity = quantity # Equivalent to Item2 quantity = 3 #(3) Instantiate to create the instantiated object item1 of the item class # The contents in the initialization are automatically executed, and do not need to be defined one by one item1 = Item('Phone') # Use the default values of price and quantity item2 = Item('MacBook', 1000, 3) # Do not use the default value, assign the value yourself # Print results print('name1:', item1.name, 'price1:', item1.price, 'quantity1:', item1.quantity) print('name2:', item2.name, 'price2:', item2.price, 'quantity2:', item2.quantity) # name1: Phone price1: 50 quantity1: 10 # name2: MacBook price2: 1000 quantity2: 3
4. initialize the method defined in the class.
Then, after class initialization, the method is defined in the class. The first parameter is instantiated object self by default. At this time, no additional parameters need to be passed in. Because the initialized object has been given attributes and attribute values, you can directly use self The property name reads the property value.
#(1) Define class class Item: #(2) Initialization. If the value of the instantiation attribute is not given during instantiation, the default value is used def __init__(self, name, price=100, quantity=10): # Assign attributes to instantiated objects self.name = name self.price = price self.quantity = quantity #(3) Define a method in a class, and self represents an instantiated object def calculate_total_price(self): # The instantiated object has been attached with attributes during initialization, which can be calculated directly in the defined method return self.price * self.quantity #(4) Create the instantiated object item1 of the item class item1 = Item('Phone', 100, 5) # Customize the value of each attribute #(5) Call the method defined in the class and pass item1 into the method as the object self res = item1.calculate_total_price() print(res) # 500 # ==2 = = supplement # The data type is not specified during the instantiation of the object. What happens if the value of the price attribute we pass in is a string item1 = Item('Phone', '100', 5) # Pass in the value of each attribute res = item1.calculate_total_price() # Call the class method to calculate the product of price and quantity # Equivalent to '100' * 5, that is, print the string 100 for 5 times print(res) # 100100100100100
However, if the type of the passed in attribute value does not meet the requirements during class instantiation, the desired result will not be obtained. For example, the price passed in is' 100 'of the string type, while the quantity is 5 of the integer type. When these two different data types are multiplied,' 100 '* 5 means that the string' 100 'is printed five times, and the result is not what we expect. Let's talk about how to deal with this situation.
5. Specify the incoming data type during initialization
Specify the data type and attribute name: data type in the initialization function. When the class is instantiated, it will remind you of the required data type. As follows, the name attribute specifies that the data type is str string type, the price attribute is floating point type, and the quantity attribute has been given a default value, so its data type is the same as that of the default value.
#(1) Create class class Item: #(2) Initialization, self represents the instantiated object # Specify that the value of the name attribute is of string type, and the value of the price attribute is of floating point type, # The quantity attribute has been attached with a default value, so there is no need to specify the type, because the data type of quantity is the data type of the default value def __init__(self, name: str, price: float, quantity=10): # Assign attributes to instantiated objects self.name = name self.price = price self.quantity = quantity #(3) Define class methods def calculate_total_price(self): # Calculate product return self.price * self.quantity #(4) Create an instantiated object of the Item class item1 = Item('Phone', 100) # Specify the name attribute and the price attribute, and the quantity attribute uses the default value #(5) Calling a method in a class res = item1.calculate_total_price() print(res) # 1000
6. During initialization, check whether the input value meets the expectation
The assert method is used here. In the previous section, we specified the data type, but what if the data type is entered correctly, but the value range does not meet the requirements. Method: assert condition, error content
As shown in the following code, assert price > = 0, f'price {price} is not greater or equal to 0 '. This means that if the attribute value received by price is greater than or equal to 0, it will run normally; If the value of price is less than 0, the program will report an error. The error content is the content after the comma.
#(1) Create a class class Item: #(2) Initialization, self represents the instantiated object, and specifies the data type of the instantiated attribute def __init__(self, name:str, price:float, quantity=10): #(3) Judge whether the input value meets the requirements. If not, an error will be reported. The error content is after the comma # For example, if the price of each instance is greater than 0, the price of each instance does not meet the requirements assert price >= 0, f'Price {price} is not greater or equal to 0' assert quantity >= 0, f'Quantity {quantity} is not greater or equal to 0' #(4) Assign a value to each instance property self.name = name self.price = price self.quantity = quantity #(5) Define class methods def calculate_total_price(self): # Calculate product return self.price * self.quantity #(6) Instantiation object item1 of item class item1 = Item('Phone', -100, 3) #(7) Call class instantiation method res = item1.calculate_total_price() print(res)