-5

以下は私のコードです。Demo クラスで google_charts クラスの関数を呼び出すことができません。問題の解決を手伝ってください。

class google_charts:
    def all_files_to_one():
        pass

    prods = []
    srcs = []
    sname = []
    def process_compiled():
        global prods, srcs, sname
        sname.append('something')
        prods.append('something')
        srcs.append('something')

def demo():
    google_charts.all_files_to_one()
    google_charts.process_compiled()

demo()

出力:

Traceback (most recent call last):
  File "C:\\demo.py", line 18, in <module>
    demo()
  File "C:\\demo.py", line 15, in demo
    google_charts.all_files_to_one()
TypeError: unbound method all_files_to_one() must be called with google_charts instance as first argument (got nothing instead)
4

4 に答える 4

4

Python でクラスを定義する場合、その中のメソッドには最初の引数として「self」が必要です。

class cheese(object):
       def some_method(self):
           return None
于 2012-09-01T07:44:18.923 に答える
2

google_contacts クラスのすべてのメソッドの署名が正しくありません。self パラメータを含める必要があります。Python クラスのドキュメントをご覧ください。

http://docs.python.org/tutorial/classes.html

これも役に立つかもしれません:

自己の目的は何ですか?

于 2012-09-01T07:48:55.317 に答える
1

使用したい:

self.all_files_to_one()

それとは別に、「self」パラメータがありません

この質問は、本当に基本的な Python オブジェクト指向プログラミングです。

試行錯誤のプログラミングをする代わりに、まず Python のチュートリアルを読んでください。

SO は、基本的なドキュメントを読むことに代わるものではありません。

于 2012-09-01T07:45:22.247 に答える
1

元の質問を自由に編集して、長くて無関係なコードを削除して、実際の問題を見えるようにしました。たくさんの関数を取り、それらをクラスでラップしただけのようです。Python クラス メソッドでは、self パラメータが必要です。元の関数はすべてall_files_to_one、クラスが操作するための状態を持たないスタイルのものでした。1 つの機能が実行されました ( process_compiled)。修正版は次のとおりです。

class google_charts(object):  # Python 2.X classes should derive from object

    # Initialize class instance state variables
    def __init__(self):
        self.prods = []  
        self.srcs = []
        self.sname = []

    # methods are called with the class instance object, traditionally named self
    def process_compiled(self):
        # Access instance variables via self
        self.sname.append('something')
        self.prods.append('something')
        self.srcs.append('something')

    # Use a static method when a method does not access class or instance state
    # but logically is associated with the class.  No self parameter is passed
    # for a static method.
    @staticmethod
    def all_files_to_one():
        print 'called all_files_to_one()'

def demo():
    gc = google_charts()  # instantiate an object
    gc.all_files_to_one() # call static method
    gc.process_compiled() # call instance method
    print gc.prods        # see some state in the instance

demo()

出力:

called all_files_to_one()
['something']

他のポスターが言及しているように、チュートリアルを読んでください。

于 2012-09-01T15:22:28.797 に答える