Python中的未绑定方法错误

Python中的未绑定方法错误,python,Python,在Python中是如何做到的(很抱歉提出了一个新手问题),您可以这样做: import shutil shutil.move(..) 这意味着可以直接使用move()方法,但在创建自己的类时 我必须先实例化它 import myclass print myclass.mymethod(...) 它给了我“必须用myclass实例调用未绑定的方法…” 关于这个未绑定和绑定的方法,我能读到什么好的文档吗?我只想使用这个方法而不需要实例化。 谢谢 那么,如果我只想按原样使用它,我应该如何编写代码呢

在Python中是如何做到的(很抱歉提出了一个新手问题),您可以这样做:

import shutil
shutil.move(..)
这意味着可以直接使用move()方法,但在创建自己的类时 我必须先实例化它

import myclass
print myclass.mymethod(...)
它给了我“必须用myclass实例调用未绑定的方法…”

关于这个未绑定和绑定的方法,我能读到什么好的文档吗?我只想使用这个方法而不需要实例化。 谢谢

那么,如果我只想按原样使用它,我应该如何编写代码呢

def mymethod()  <----- defined here?
class myclass:
   def __init__ ....
   def mymethod(self)....  <----- define here will give me error w/o instantiation

def mymethod()只要提供实例作为第一个参数(self),就可以使用类名调用该方法。这也适用于您的类。

如果可以在没有实例的情况下调用您的方法,那么您可以添加decorator
@static\u方法
,以允许在没有实例的情况下调用它。python手册对此进行了详细介绍。

您似乎认为必须将函数放入类中

情况并非如此。
shutil
不是一个类,它是一个模块。
shutil
模块定义的唯一类是例外;文档化API中的所有其他内容都是顶级函数。您可以查看;
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
是同一模块中的其他公共函数,
\u samefile
\u basename
\u destinrc
是同一模块中不属于公共API的函数


毕竟,Python不是Java;Java将每个文件限制为一个类,名称相同,并且所有代码必须是类的一部分。在Python中,类是完全可选的。

ascii\u大写()
是一个函数,而不是一个方法。
mymethod
为什么首先是一个方法?如果你想直接使用它,为什么还要把它放在一个类中?@MartijnPieters从技术上讲函数和方法不是一回事?@Haidro:方法是包装器对象。它们是在函数用作描述符时生成的。函数用作在实例或类上查找描述符(在Python 3中,只有在实例上时,函数描述符才会返回自身。Ohh…现在我明白了!!为了将我的函数组合在一起,我总是可以在Python文件中对它们进行分组,而无需创建类。天哪..太简单了。自己动手吧