0

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
4

3 に答える 3

1

関数をクラスに配置する必要があるという印象を受けているようです。

これはそうではありません。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)

ここでcopytreermtreecopy2は同じモジュール内の他のパブリック関数であり_samefile_basenameと と_destinsrcは同じモジュール内の関数であり、パブリック API の一部であることを意図していません。

結局のところ、Python は Java ではありません。Java では、同じ名前のファイルごとに 1 つのクラスに制限されており、すべてのコードはクラスの一部である必要があります。Python では、クラスは完全にオプションです。

于 2013-09-09T09:17:28.513 に答える
0

インスタンスなしでメソッドを呼び出すことができる場合は、デコレータ@static_methodを追加して、インスタンスなしでメソッドを呼び出すことができます。python マニュアルはこれをよくカバーしています。

于 2013-09-09T07:56:52.543 に答える
0

インスタンスを第 1 引数 (self) として指定する限り、クラス名を使用してメソッドを呼び出すことができます。これはあなたのクラスでも機能します。

于 2013-09-09T07:54:30.867 に答える