Python 抽象在编程中意味着什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21220155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does abstraction mean in programming?
提问by copper
I'm learning python and I'm not sure of understanding the following statement : "The function (including its name) can capture our mental chunking, or abstraction, of the problem."
我正在学习 python,但我不确定是否理解以下语句:“函数(包括它的名称)可以捕获我们对问题的心理组块或抽象。”
It's the part that is in bold that I don't understand the meaning in terms of programming. The quote comes from http://www.openbookproject.net/thinkcs/python/english3e/functions.html
粗体部分是我不理解编程方面的含义。引用来自http://www.openbookproject.net/thinkcs/python/english3e/functions.html
How to think like a computer scientist, 3 edition.
如何像计算机科学家一样思考,第 3 版。
Thank you !
谢谢 !
采纳答案by miraculixx
Abstraction is a core concept in all of computer science. Without abstraction, we would still be programming in machine code or worse not have computers in the first place. So IMHO that's a really good question.
抽象是所有计算机科学的核心概念。如果没有抽象,我们仍然会使用机器代码进行编程,或者更糟的是,一开始就没有计算机。所以恕我直言,这是一个非常好的问题。
What is abstraction
什么是抽象
Abstractingsomething means to give namesto things, so that the name captures the core of what a function or a whole program does.
抽象某物意味着给事物命名,以便名称捕捉到一个函数或整个程序所做的事情的核心。
One example is given in the book you reference, where it says
你参考的书中给出了一个例子,它说
Suppose we're working with turtles, and a common operation we need is to draw squares. “Draw a square” is an abstraction, or a mental chunk, of a number of smaller steps. So let's write a function to capture the pattern of this “building block”:
假设我们正在处理海龟,我们需要的一个常见操作是绘制正方形。“画一个正方形”是许多较小步骤的抽象或心理块。因此,让我们编写一个函数来捕获这个“积木”的模式:
Forget about the turtles for a moment and just think of drawing a square. If I tell you to draw a square (on paper), you immediately know what to do:
暂时忘记海龟,只想画一个正方形。如果我告诉你画一个正方形(在纸上),你会立即知道该怎么做:
- draw a square => draw a rectangle with all sides of the same length.
- 画一个正方形 =>画一个四边都等长的长方形。
You can do this without further questions because you know by heart what a squareis, without me telling you step by step. Here, the word squareis the abstractionof "draw a rectangle with all sides of the same length".
您无需再问其他问题就可以做到这一点,因为您已经牢记正方形是什么,而无需我一步一步地告诉您。在这里,正方形这个词是“画一个所有边长相同的矩形”的抽象。
Abstractions run deep
抽象深入
But wait, how do you know what a rectangleis? Well, that's another abstraction for the following:
但是等等,你怎么知道什么是矩形?好吧,这是以下内容的另一个抽象:
- rectangle=> draw two lines parallel to each other, of the same length, and then add another two parallel lines perpendicular to the other two lines, again of the same length but possibly of different length than the first two.
- 矩形=> 绘制两条彼此平行、长度相同的线,然后添加另外两条与其他两条线垂直的平行线,同样长度相同,但可能与前两条线的长度不同。
Of course it goes on and on - lines, parallel, perpendicular, connectingare all abstractionsof well-known concepts.
当然,它继续和在线,平行,垂直,连接都是众所周知的概念的抽象。
Now, imagine each time you want a rectangle or a square to be drawn you have to give the full definition of a rectangle, or explain lines, parallel lines, perpendicular lines and connecting lines -- it would take far too long to do so.
现在,想象一下每次要绘制矩形或正方形时,您都必须给出矩形的完整定义,或者解释直线、平行线、垂直线和连接线——这样做会花费太长时间。
The real power of abstraction
抽象的真正力量
That's the first power of abstractions:they make talking and getting things done much easier.
这是抽象的第一个力量:它们使谈话和完成事情变得更加容易。
The second power of abstractions comes from the nice property of composability: once you have defined abstractions, you can composetwo or more abstractions to form a new, larger abstraction: say you are tired of drawing squares, but you really want to draw a house. Assume we have already defined the triangle, so then we can define:
抽象的第二个力量来自可组合性的良好属性:一旦你定义了抽象,你就可以组合两个或更多的抽象来形成一个新的、更大的抽象:假设你厌倦了画正方形,但你真的想画一座房子. 假设我们已经定义了三角形,那么我们可以定义:
- house=> draw a squarewith a triangleon top of it
- 房子=> 画一个正方形,上面有一个三角形
Next, you want a village:
接下来,你想要一个村庄:
- village=> draw multiple housesnext to each other
- 村庄=> 绘制多个相邻的房屋
Oh wait, we want a city -- and we have a new concept street:
哦等等,我们想要一座城市——而且我们有一条新概念街道:
- city=> draw many villagesclose to each other, fill empty spaces with more houses, but leave room for streets
- street=> (some definition of street)
- 城市=> 将许多村庄彼此靠近,用更多房屋填充空地,但为街道留出空间
- street=>(街道的一些定义)
and so on...
等等...
How does this all apply to programmming?
这一切如何应用于编程?
If in the course of planning your program (a process known as analysis and design), you find good abstractions to the problem you are trying to solve, your programs become shorter, hence easier to write and - maybe more importantly - easier to read. The way to do this is to try and grasp the major concepts that define your problems -- as in the (simplified) example of drawing a house, this was squaresand triangles, to draw a villageit was houses.
如果在计划程序的过程中(称为分析和设计的过程),您发现对要解决的问题有很好的抽象,那么您的程序就会变得更短,因此更容易编写,而且——也许更重要的是——更容易阅读。这样做的方法是尝试掌握定义您的问题的主要概念——如在绘制房屋的(简化)示例中,这是正方形和三角形,绘制村庄则是房屋。
In programming, we define abstractions as functions (and some other constructs like classes and modules, but let's focus on functions for now). A function essentially namesa set of single statements, so a function essentially is an abstraction -- see the examples in your book for details.
在编程中,我们将抽象定义为函数(以及其他一些构造,如类和模块,但现在让我们关注函数)。函数本质上是命名一组单个语句,因此函数本质上是一种抽象——有关详细信息,请参阅您书中的示例。
The beauty of it all
这一切的美丽
In programming, abstractions can make or break productivity. That's why often times, commonly used functions are collected into librarieswhich can be reused by others. This means you don't have to worry about the details, you only need to understand how to use the ready-made abstractions. Obviously that should make things easier for you, so you can work faster and thus be more productive:
在编程中,抽象可以成就或破坏生产力。这就是为什么很多时候,常用的函数被收集到可以被其他人重用的库中。这意味着您不必担心细节,您只需要了解如何使用现成的抽象。显然,这会让您的工作更轻松,因此您可以更快地工作,从而提高工作效率:
Example:
示例:
Imagine there is a graphics library called "nicepic" that contains pre-defined functions for all abstractions discussed above: rectangles, squares, triangles, house, village.
想象一下,有一个名为“nicepic”的图形库,其中包含用于上述所有抽象的预定义函数:矩形、正方形、三角形、房屋、村庄。
Say you want to create a program based on the above abstractions that paints a nice picture of a house, all you have to write is this:
假设您想基于上述抽象创建一个程序来绘制一幅漂亮的房子图片,您只需编写以下代码:
import nicepic
draw_house()
So that's just two lines of code to get something much more elaborate. Isn't that just wonderful?
所以这只是两行代码来获得更复杂的东西。这不是很美妙吗?
Hope this helps.
希望这可以帮助。
回答by Justin Poehnelt
As defined on wikipedia: Abstraction_(computer_science)
如维基百科所定义:Abstraction_(computer_science)
Abstraction tries to factor out details from a common pattern so that programmers can work close to the level of human thought, leaving out details which matter in practice, but are not exigent to the problem being solved.
抽象试图从一个共同的模式中提取出细节,这样程序员就可以接近人类思维的水平,而忽略在实践中很重要但对解决的问题并不重要的细节。
Basically it is removing the details of the problem. For example, to draw a square requires several steps, but I just want a function that draws a square.
基本上它是删除问题的细节。例如,绘制一个正方形需要几个步骤,但我只想要一个绘制正方形的函数。
回答by bedane
Let's say you write a function which receives a bunch of text as parameter, then reads credentials in a config file, then connects to a SMTP server using those credentials and sends a mail using that text.
假设您编写了一个函数,它接收一堆文本作为参数,然后读取配置文件中的凭据,然后使用这些凭据连接到 SMTP 服务器并使用该文本发送邮件。
The function should be named sendMail(text), not parseTextReadCredentialsInFileConnectToSmtpThenSend(text)because it is more easy to represent what it does this way, to yourself and when presenting the API to coworkers or users... even though the 2nd name is more accurate, the first is a better abstraction.
该函数应命名为sendMail(text),而不是parseTextReadCredentialsInFileConnectToSmtpThenSend(text)因为它更容易向您自己以及向同事或用户展示 API 时以这种方式表示它的作用......即使第二个名称更准确,第一个是更好的抽象。
回答by dursk
A great way to understand abstraction is through abstract classes.
理解抽象的一个好方法是通过抽象类。
Say we are writing a program which models a house. The house is going to have several different rooms, which we will represent as objects. We define a class for a Bathroom, Kitchen, Living Room, Dining Room, etc.
假设我们正在编写一个模拟房屋的程序。房子将有几个不同的房间,我们将它们表示为对象。我们为浴室、厨房、客厅、餐厅等定义了一个类。
However, all of these are Rooms, and thus share several properties (# of doors/windows, square feet, etc.) BUT, a Room can never exist on it's own...it's always going to be some typeof room.
然而,所有这些都是房间,因此共享几个属性(门/窗数量、平方英尺等)但是,房间永远不会单独存在......它总是会是某种类型的房间。
It then makes sense to create an abstract class called Room, which will contain the properties all rooms share, and then have the classes of Kitchen, Living Room, etc, inherit the abstract class Room.
然后创建一个名为 Room 的抽象类是有意义的,该类将包含所有房间共享的属性,然后让 Kitchen、Living Room 等类继承抽象类 Room。
The concept of a room is abstractand only exists in our head, because any room that actuallyexists isn't just a room; it's a bedroom or a living room or a classroom.
房间的概念是抽象的,只存在于我们的脑海中,因为任何实际存在的房间都不仅仅是一个房间;它是卧室、客厅或教室。
We want our code to thus represent our "mental chunking". It makes everything a lot neater and easier to deal with.
我们希望我们的代码能够代表我们的“心理组块”。它使一切都变得更整洁,更容易处理。
回答by Steven Leggett
The best way to to describe something is to use examples:
描述某事的最佳方式是使用示例:
A function is nothing more than a series of commands to get stuff done. Basically you can organize a chunk of code that does a single thing. That single thing can get re-used over and over and over through your program.
一个函数只不过是一系列用来完成任务的命令。基本上,您可以组织一大段代码来完成一件事情。这个单一的东西可以在你的程序中一遍又一遍地重复使用。
Now that your function does this thing, you should name it so that it's instantly identifiable as to what it does. Once you have named it you can re-use it all over the place by simply calling it's name.
既然你的函数做了这件事,你应该给它命名,以便它可以立即识别它的作用。一旦你命名了它,你就可以通过简单地调用它的名字来重复使用它。
def bark():
print "woof!"
Then to use that function you can just do something like:
然后要使用该功能,您可以执行以下操作:
bark();
What happens if we wanted this to bark 4 times? Well you could write bark(); 4 times.
如果我们想让它吠 4 次会发生什么?那么你可以写 bark(); 4次。
bark();
bark();
bark();
bark();
Or you could modify your function to accept some type of input, to change how it works.
或者您可以修改您的函数以接受某种类型的输入,以更改其工作方式。
def bark(times):
i=0
while i < times:
i = i + 1
print "woof"
Then we could just call it once:
然后我们可以只调用一次:
bark(4);
When we start talking about Object Oriented Programming (OOP) abstraction means something different. You'll discover that part later :)
当我们开始谈论面向对象编程 (OOP) 时,抽象意味着不同的东西。你稍后会发现那部分:)
回答by Bubba Yakoza
Abstraction:is a very important concept both in hardware and software.
抽象:在硬件和软件中都是一个非常重要的概念。
Importance:We the human can not remember all the things all the times. For example, if your friend speaks 30 random numbers quickly and asks you to add them all, it won't be possible for you. Reason? You might not be able to keep all those numbers in mind. You might write those numbers on a paper even then you will be adding right most digits one by one ignoring the left digits at one time and then ignoring the right most digits at the other time having added the right most ones.
重要性:我们人类不可能一直记住所有的事情。例如,如果您的朋友快速说出 30 个随机数并要求您将它们全部添加,您就不可能。原因?您可能无法记住所有这些数字。您可能会在纸上写下这些数字,即使您将一个一个地添加最右边的数字,一次忽略左边的数字,然后在添加最右边的数字后忽略最右边的数字。
It shows that at one time we the human can focusat some particular issue while ignoring those which are already solved and moving focus towards what are left to be solved.
它表明,在某一时刻,我们人类可以专注于某个特定问题,而忽略那些已经解决的问题,而将注意力转移到有待解决的问题上。
Ignoring less important thing and focusing the most important (for the time being and in particular context) is called Abstraction
忽略不太重要的事情而专注于最重要的事情(暂时,特别是上下文)称为抽象
Here is how abstraction works in programming.
以下是抽象在编程中的工作原理。
Below is the world's famous hello world program in C language:
下面是世界著名的C语言hello world程序:
//C hello world example hello.c
#include <stdio.h>
int main()
{
printf("Hello world\n");
return 0;
}
This is the simplest and usually the first computer program a programmer writes. When you compile and run this program on command prompt, the output may appear like this:
这是程序员编写的最简单且通常是第一个计算机程序。在命令提示符下编译并运行此程序时,输出可能如下所示:
Here are the serious questions
这里是严肃的问题
- Computer only understands the binary code how was it able to run your English like code? You may say that you compiled the code to binary using compiler. Did you write compiler to make your program work? No. You needed not to. You installed GNU C compiler on your Linux system and just used it by giving command:
- 计算机只懂二进制代码,它怎么能像代码一样运行你的英语?您可能会说您使用编译器将代码编译为二进制。您是否编写了编译器来使您的程序工作?不,你不需要。您在 Linux 系统上安装了 GNU C 编译器,并通过给出命令来使用它:
gcc -o hello hello.c
gcc -o 你好你好.c
And it converted your English like C language code to binary code and you could run that code by giving command:
它将您的英语(如 C 语言代码)转换为二进制代码,您可以通过给出命令来运行该代码:
./hello
。/你好
So, for writing an application in C program, you never need to know how C compiler converts C language code to binary code. So you used GCC compiler as an abstraction.
因此,要在 C 程序中编写应用程序,您永远不需要知道 C 编译器如何将 C 语言代码转换为二进制代码。所以你使用 GCC 编译器作为抽象。
- Did you write code for main() and printf() functions? No. Both are already defined by someone else in C language. When we run a C program, it looks for main() function as starting point of program while printf() function prints output on computer screen and is already defined in stdio.h so we have to include it in program. If both the functions were not already written, we had to write them ourselves just to print two words and computers would be the most boring machines on earth ever. Here again you use abstraction i.e. you don't need to know how printf prints text on monitor and all you need to know is how to give input to printf function so that it shows the desired output.
- 您是否为 main() 和 printf() 函数编写了代码?不。两者都已经被其他人用 C 语言定义了。当我们运行一个 C 程序时,它寻找 main() 函数作为程序的起点,而 printf() 函数在计算机屏幕上打印输出并且已经在 stdio.h 中定义,所以我们必须将它包含在程序中。如果这两个函数还没有写出来,我们就必须自己编写它们来打印两个字,而计算机将是地球上最无聊的机器。在这里你再次使用抽象,即你不需要知道 printf 如何在监视器上打印文本,你需要知道的是如何为 printf 函数提供输入,以便它显示所需的输出。
I did not expand the answer to abstraction of operating system, kernel, firmware and hardware for the sake of simplicity.
为简单起见,我没有将答案扩展到操作系统、内核、固件和硬件的抽象。
Things to remember:
要记住的事情:
While doing programming, you can use abstraction in a variety of ways to make your program simple and easy.
在进行编程时,您可以通过多种方式使用抽象来使您的程序简单易行。
Example 1: You can use a constantto abstract value of PI 3.14159 in your program because PI is easy to remember than 3.14159 for the rest of program
示例 1:您可以在程序中使用常量来抽象 PI 3.14159 的值,因为 PI 比程序其余部分的 3.14159 更容易记住
Example 2: You can write a functionwhich returns square of a given number and then anyone, including you, can use that function by giving it input as parameters and getting a return value from it.
示例 2:您可以编写一个返回给定数字的平方的函数,然后任何人(包括您)都可以通过将输入作为参数并从中获取返回值来使用该函数。
Example 3: In an Object-oriented programming (OOP), like Java, you may define an objectwhich encapsulates data and methods and you can use that object by invoking its methods.
示例 3:在面向对象的编程 (OOP) 中,例如 Java,您可以定义一个封装数据和方法的对象,并且您可以通过调用其方法来使用该对象。
Example 4: Many applications provide you APIwhich you use to interact with that application. When you use API methods, you never need to know how they are implemented. So abstraction is there.
示例 4:许多应用程序为您提供用于与该应用程序交互的API。当您使用 API 方法时,您永远不需要知道它们是如何实现的。所以抽象是存在的。
Through all the examples, you can realize the importance of abstraction and how it is implemented in programming. One key thing to remember is that abstraction is contextual i.e. keeps on changing as per context
通过所有示例,您可以意识到抽象的重要性以及它是如何在编程中实现的。要记住的一件关键事情是抽象是上下文的,即根据上下文不断变化
回答by Alireza Rahmani Khalili
In a simple sentence, I can say: The essence of abstraction is to extract essential properties while omitting inessential details. But why should we omit inessential details? The key motivator is preventing the risk of change.
用简单的一句话,我可以说:抽象的本质是提取本质属性,同时省略无关紧要的细节。但是我们为什么要省略无关紧要的细节呢?关键的动力是防止变化的风险。


