问题
I have noticed that considerably amount of questions in SO, relating to Python, are about people messing up Sys -class, OS class and no class. For example, an easy confusing is the case: os.open("something")
, open("something")
and sys.open("something")
. I haven't understood yet the reasons behind the naming of classes, perhaps it is just an evolution.
- I would like to hear
why
they were created with their current names? - Are naming due to things like having FDs in a class?
- Is naming because some classes require special privileges?
- To which extent is the naming a design solution?
If you cannot answer the question, feel free to suggest some good mnemonics to memorize the classes and to differentiate them.
回答1:
Built-in functions are things that you need often. You do not have to import any module to access them, and thus don't use any module prefix either. open()
is one such function, since opening files is a very common operation. It opens a file and returns a file object, which is easy to use.
The os
module is for operating system interfaces. os.open()
is a raw interface to the file interface of the operating system. It opens a file and returns the bare file descriptor, which you do not normally need for anything.
The sys
module is for system-specific things. sys.open()
does not exist.
回答2:
Easy confusing is lies in the case: os.open("something"), open("something") and sys.open("something").
A "mnemonic" is the documentation, available on-line or downloaded to your workstation.
Built-in
open
: http://docs.python.org/library/functions.html#open "Open a file"os.open
: http://docs.python.org/library/os.html#os.open "This function is intended for low-level I/O."sys.open
doesn't exist.io.open
: http://docs.python.org/library/io.html#io.open "in Python 3.x it is the default interface to access files and streams"
The "mnemonic" is easy. Use the one that matches your requirements.
why they were created with their current names
To keep clutter out of the language an in separate libraries.
Are naming due to things like having FDs in a class?
Probably. FD's are an OS feature, not a language feature. That's why they're in a separate library.
Is naming because some classes require special privileges?
Not at all.
To which extent is the naming a design solution?
To keep clutter out of the language an in separate libraries.
来源:https://stackoverflow.com/questions/5602439/reasons-behind-naming-in-easy-to-confuse-pythons-classes-such-as-os-and-sys