How Python consolidates functions and data, and accesses them through the name of an object.
How and why to use classes and objects, and how they make it easier for programmers to write and use programs in many situations.
3.1 Considering programming
Now to create a description of the object in Python, you have enough to just get two views. The first is the Data view, which can be used and purged as needed, in addition to the top level or global scope data. Another function view, they have no intrinsic data, but manipulate the data provided to them.
Meaning of the 3.1.1 object
Any one data has objects, each of which consists of 3 parts: Identity, type, and value. An object's identity represents the location (immutable) where the object is stored in memory, and the type of the object indicates that it can have a type of data and value, in which the value of the mutable type can be changed, and the value of the immutable type cannot be changed.
The simple explanation is to refer to the object already described in this book. For example, integers, strings, lists, and so on are all objects. It's easy to use these objects in your program, but isn't it more meaningful to integrate tightly knit objects together? This is the origin of the class, which allows you to define a set of objects and encapsulate them in a convenient space.
3.1.2 already know the object
3.1.3 How to use objects
3.2 Defining classes
When you think about how a small program that contains hundreds of lines of Python code works, you can often find that the program organizes the data into groups-when you access a data, it affects the data that is working with that data. A complete list of data with dependencies is often encountered, such as the first element of Listing 1 and the first element in List 2 and listing 3. Sometimes, you must combine these lists creatively to solve this problem. Python uses the concept of creating an entire class to be used as a placeholder, which acts as a placeholder and creates an object that is bound to a name when a class is called.
3.2.1 How to create an object
Define a class
Use the keyword class, followed by a name to complete.
class Fridge:
Create an object from a class
>>>f=fridge ()
There is no complex class defined at this time, and the fridge class is basically empty, which serves as a starting point. However, even if he is empty, it should be noted that a usable empty class has been created and that it is almost no operation.
Taking a few minutes to see the _init_ and self parts is two very important characteristics of the class, and when Python creates the object, the _init_ method passes to the object's first argument. And self is actually a variable that represents the instance itself.
Writing internal methods
This internal method, cannot determine whether the current type is valid, should be used to detect the interface function. It is a good idea to check every place allowed, but in this case, it is not intended to be checked here, because the _add_multi method is only used in a very simple way.
Writing interface Methods
To make it faster, you can now do not enter a document string, where the method allows you to better understand the actual operation of the code in case of problems.
These methods need to be indented in the definition of the fridge class, and any code that looks like the initial position of each line is actually a continuation of the previous row and should be entered on the same line:
defAdd_one (Self, food_name):ifType (food_name)! = Type (""): RaiseTypeError,"Add_one requires a string,given a%s"%type (food_name)Else: Self._add_multi (Food_name,1) returnTruedefAdd_many (Self, food_dict):ifType (food_dict)! =type ({}):RaiseTypeError ("Add_many requires a dictionary,got a%s"food_dict) forIteminchFood_dict.keys (): Self._add_multi (item, Food_dict[item])return
The purpose of Add_one and Add_many is similar, and each method has code that ensures that they are used correctly, and they can use the Add-multi to do the main work. Now, if Add-multi's work style changes, developers can save time because it will automatically change the way the two methods that use it behave.
Now you have written enough code to put food in the Frige object, but there is no way to take the food out of the refrigerator. You can access the Object.items dictionary directly, but this is not a good idea in addition to testing. But now is the test, why not do it?
>>>f = Fridge ({"eggs": 6,"Milk": 4,"Cheese": 3})>>>f.items{'Cheese': 3,'eggs': 6,'Milk': 4}>>>f.add_one ("Grape") True>>>f.items{'Cheese': 3,'eggs': 6,'Grape': 1,'Milk': 4}>>>f.add_many ({"Mushroom"75A"Tomato": 3})>>>f.items{"Tomato": 3,'Cheese': 3,'Grape': 1,'Mushroom'75A'eggs': 6,'Milk': 4}
The code you've entered so far has worked, and then you need to add a way to tell if something is in the refrigerator.
Writing code is really important if something is present in the refrigerator because it can be used to take out food methods such as get_one,get_many,get_ingredients, so that these methods can check if there is enough food in the refrigerator, which is what has and Has_ The purpose of the various method.
defHas (Self,food_name,quantity=1): returnself.has_various ({food_name:quantity})defhas_various ({self,foods):Try: forFoodinchFoods.keys ():ifSelf.items[food] <Foods[food]:returnFalsereturnTrueexceptKeyerror:returnFalse
Use more methods:
You can now invoke the ch6.py file using the Python-i or run with interpreter command, which allows you to use any code that is price-coded to the fridge class. If an error occurs instead of the >>> prompt, note the exception that is thrown, and try to fix the indentation problem, spelling error, or other basic error.
The fridge class can be used as follows:
>>>f = Fridge ({ eggs Span style= "color: #800000;" > ": 6," mike : 4," Cheese : 3 >>>if F.has ( cheese ", 2 print ( its time to make an omelet " " ... its time-to-make an omelet
Example Description: New methods are now defined, F objects can use them, when the F object is re-created with egg milk and cheese, the object is created from the new fridge class, so it has the newly added available method.
Finally, we should discuss the method of taking food from the refrigerator. Similar to how food is added to the refrigerator, the main work is done by a core approach, and all interface methods are dependent on this method.
def_get_multi (self,food_name,quantity):Try: if(Self.items[food_name] isNone):returnFalse; if(quantity>Self.items[food_name]):returnFalse; Self.items[food_name]= self.items[food_name]-QuantityexceptKeyerror:returnFalsereturnQuantity
Once defined, you can create a method specified by the document string, where each method uses _get_multi, so you can remove the food from the refrigerator with minimal extra code:
3.2.2 Objects and their scopes
The function creates its own space for the name that they use, which is the scope. When a function is called, and after the name is declared and given a value, any modification to that name will persist as long as the function is still in use. However, after the function finishes running and is called here, the work done in the previous electrophoresis process is lost and the function must be restarted.
The values in the object can be stored and associated with self, meaning self is pointing to the object.
Create a different class:
We created a fridge class and now create the Omelet class:
Now there is a class, and its purpose is clear. The Omelet class has an interface method that allows it to collaborate with the fridge object, and it still has the ability to create a specified omelet.
The following code must indent a level under the Omelet class definition:
def_ingredients_ (self):returnself.needed_ingredientsdefGet_kind (self):returnSelf.kinddefSet_kind (self,kind): Possible_ingredients=self._known_kinds (kind)ifPossible_ingredients = =False:returnFalseElse: Self.kind=Kind Self.needed_ingredients=possible_ingredientsdefSet_new_kind (self,name,ingredients): Self.kind=name Self.needed_ingredients=Ingredientsreturndef_known_kind (self,kind):ifKind = ="Cheese": return{"eggs": 2,"Mike": 1,"Cheese": 1} elifKind = ="Mushroom": return{"eggs": 2,"Mike": 1,"Cheese": 1,"Mushroom": 2} elifKind = ="Onion": return{"eggs": 2,"Mike": 1,"Cheese": 1,"Onion": 1} Else: Self.kind=Kind Self.needed_ingredients=Ingredientsreturndefget_kown_kinds (Self,fridge): Self.from_fridge=fridge.get_ingredients (self)defMix (self): forIngredientinchSelf.from_fridge.keys ():Print("Mixing%d%s for the%s omelet"%self.from_fridge[ingredient],ingredient,self.kind) self.mixed=truedefMake (self):ifSelf.mixed = =true:Print("Cooking the%s omelet!"%self.kind) self.cooked=true
There is now a omelet class that can create Omelet objects, and the Omelet class has the same characteristics as the omelet. And the external manifestations of omelet are concentrated into several simple interfaces
There are now two classes that can be used to make an omelet after loading them with the python-i or run with interpreter command:
We can also make multiple omelets:
This way of programming, we call it object-oriented and why it is used to make large systems.
Python functions (Chapter III: Classes and objects)