我无法在另一个类中调用一个类的函数

时间:2012-09-01 07:37:47

标签: python python-2.7

以下是我的代码。我无法在我的Demo课程中调用google chart类的功能。帮我解决问题。

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 个答案:

答案 0 :(得分:4)

在python中定义一个类时,其中的任何方法都必须将'self'作为第一个agrument:

class cheese(object):
       def some_method(self):
           return None

答案 1 :(得分:2)

google_contacts类中所有方法的签名都不正确。它们必须包含self参数。看一下Python类的文档:

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

这也可能有用:

What is the purpose of self?

答案 2 :(得分:1)

您想使用:

self.all_files_to_one()

除此之外:缺少'self'参数

这个问题是真正基本的Python面向对象编程。

请先阅读Python教程,然后再尝试使用试错法。

SO不能替代阅读基本文档。

答案 3 :(得分:1)

我冒昧地编辑原始问题,删除长而无关的代码,以使实际问题可见。看起来你已经采取了一堆函数,只是围绕它们包装了一个类。在Python类中,方法需要一个self参数。原始函数都是样式all_files_to_one,它们没有类可以操作的状态。一个功能(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']

请阅读其他海报提到的教程。