【问题标题】:calling a function in python got nothing instead [closed]在python中调用函数一无所获[关闭]
【发布时间】:2026-02-04 13:05:01
【问题描述】:

我得到了这样的代码。

....
class SocketWatcher(Thread):
    ....
    def run(self):
       ....
       TicketCounter.increment()  # I try to get this function  
       ...
....
class TicketCounter(Thread):
    ....
    def increment(self):
    ...

当我运行程序时出现此错误。

TypeError: unbound method increment() must be called with TicketCounter instance as first argument (got nothing instead)

我有什么方法可以从 TicketCounter 类调用 increment() 函数到 SocketWatcher 类?还是我的电话有误...

【问题讨论】:

  • 评论很明显。你可以阅读它并在谷歌上搜索一下以得到答案。

标签: python function class


【解决方案1】:

您必须先创建类TicketCounter 的实例,然后才能从中调用任何函数:

class SocketWatcher(Thread):
    ....
    def run(self):
       ....
       myinstance = TicketCounter()
       myinstance.increment()

否则该方法不会在任何地方绑定。创建实例会将方法绑定到实例。

【讨论】:

    【解决方案2】:

    成员函数是类实例的一部分。因此,无论何时您要调用,都必须始终使用类的实例而不是类名本身来调用它。

    你可以这样做:

    TicketCounter().increment()

    它的作用是初始化一个对象,然后调用这个函数。下面的例子就清楚了。

    class Ticket:
    
        def __init__(self):
    
            print 'Object has been initialised'
    
        def counter(self):
    
            print "The function counter has been invoked"
    

    以及说明这一点的输出:

    >>> Ticket().counter()
    Object has been initialised
    The function counter has been invoked
    >>> 
    

    【讨论】:

      【解决方案3】:

      您正在传递自我,所以我假设您需要创建一个实例。但是,如果该方法确实不需要实例,那么您可以使用 @classmethod@staticmethod 装饰器,您的代码就可以工作:

      class TicketCounter(Thread):
          @classmethod
          def increment(cls):
              ...
      

      class TicketCounter(Thread):
          @staticmethod
          def increment():
              ...
      

      两者都可以称为TicketCounter.increment()

      【讨论】: