您似乎认为必须将函数放在类中。
不是这种情况。shutil
不是一个类,它是一个模块。shutil
模块定义的唯一类是异常;文档化 API 中的所有其他内容都是顶级函数。你可以看看shutil
源代码;该move
函数在模块源代码中直接定义为:
def move(src, dst):
"""Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.
If the destination already exists but is not a directory, it may be
overwritten depending on os.rename() semantics.
If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed.
A lot more could be done here... A look at a mv.c shows a lot of
the issues this implementation glosses over.
"""
real_dst = dst
if os.path.isdir(dst):
if _samefile(src, dst):
# We might be on a case insensitive filesystem,
# perform the rename anyway.
os.rename(src, dst)
return
real_dst = os.path.join(dst, _basename(src))
if os.path.exists(real_dst):
raise Error, "Destination path '%s' already exists" % real_dst
try:
os.rename(src, real_dst)
except OSError:
if os.path.isdir(src):
if _destinsrc(src, dst):
raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
copytree(src, real_dst, symlinks=True)
rmtree(src)
else:
copy2(src, real_dst)
os.unlink(src)
其中copytree
,rmtree
和copy2
是同一模块中的其他公共函数,并且_samefile
,_basename
和_destinsrc
是同一模块中不属于公共 API 的函数。
毕竟 Python 不是 Java。Java 将您限制为每个文件一个类,具有相同的名称,并且所有代码都必须是类的一部分。在 Python 中,类是完全可选的。