在python中调用函数没有得到任何结果

在python中调用函数没有得到任何结果,python,function,class,Python,Function,Class,我有这样的密码 .... class SocketWatcher(Thread): .... def run(self): .... TicketCounter.increment() # I try to get this function ... .... class TicketCounter(Thread): .... def increment(self): ... 当我运行程序时,我遇到了这个错

我有这样的密码

....
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类?或者我的调用是错误的…

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

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

否则,该方法不会绑定到任何位置。创建实例会将方法绑定到实例。

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

你可以做:

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
>>> 

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

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


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

注释非常明显。你本可以阅读它,然后在谷歌上搜索一下以得到答案。
class TicketCounter(Thread):
    @staticmethod
    def increment():
        ...