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

2024-09-30 01:32:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的密码。在

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

当我运行这个程序时,我遇到了这个错误。在

^{pr2}$

我有没有办法把increment()函数从TicketCounter类调用到SocketWatcher类?还是我的电话错了。。。在


Tags: torunself程序密码getdeffunction
3条回答

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

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

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

您正在传递self,所以我假设您需要创建一个实例。但是,如果该方法确实不需要实例,那么可以使用@classmethod或{}修饰符,代码就可以工作了:

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

或者

^{pr2}$

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

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

你可以:

TicketCounter().increment()

它的作用是初始化一个对象,然后调用这个函数。下面的例子将说明这一点。在

class Ticket:

    def __init__(self):

        print 'Object has been initialised'

    def counter(self):

        print "The function counter has been invoked"

以及说明这一点的输出:

^{pr2}$

相关问题 更多 >

    热门问题