我有这样的密码。在
....
class SocketWatcher(Thread):
....
def run(self):
....
TicketCounter.increment() # I try to get this function
...
....
class TicketCounter(Thread):
....
def increment(self):
...
当我运行这个程序时,我遇到了这个错误。在
^{pr2}$我有没有办法把increment()函数从TicketCounter类调用到SocketWatcher类?还是我的电话错了。。。在
必须先创建类
TicketCounter
的实例,然后才能从中调用任何函数:否则该方法不会绑定到任何地方。创建实例将方法绑定到实例。在
您正在传递self,所以我假设您需要创建一个实例。但是,如果该方法确实不需要实例,那么可以使用}修饰符,代码就可以工作了:
@classmethod
或{或者
^{pr2}$两者都可以称为
TicketCounter.increment()
成员函数是类实例的一部分。因此,无论何时调用,都必须使用类的实例而不是类名本身来调用它。在
你可以:
TicketCounter().increment()
它的作用是初始化一个对象,然后调用这个函数。下面的例子将说明这一点。在
以及说明这一点的输出:
^{pr2}$相关问题 更多 >
编程相关推荐