如何在python中从不同的类启动或调用函数?
嘿,伙计们需要知道如何从类B开始在类a中启动方法 有 这是一个错误如何在python中从不同的类启动或调用函数?,python,python-2.7,Python,Python 2.7,嘿,伙计们需要知道如何从类B开始在类a中启动方法 有 这是一个错误 TypeError: unbound method multiplyPeople() must be called with classB instance as first argument (got nothing instead) 我知道这是一件基本的事情,但我正试图弄清楚到底应该做什么,我在哪里迷路了 我称之为 classA(object): def__init__(self): self.Peo
TypeError: unbound method multiplyPeople() must be called
with classB instance as first argument (got nothing instead)
我知道这是一件基本的事情,但我正试图弄清楚到底应该做什么,我在哪里迷路了
我称之为
classA(object):
def__init__(self):
self.PeopleVariable=classB.multiplyPeople()
这取决于您希望函数如何工作。是否只想将该类用作占位符?然后,您可以使用所谓的静态方法,而无需为其实例化对象 或者您可以使用常规方法并在创建的对象上使用它(请注意,您可以在那里访问
self
)
输出:
<__main__.B instance at 0x7f3d2ab5d710> was called
this was called
调用了
这叫做
您是如何尝试调用它的?能否显示更多代码?对于您提供的代码,它与您提供的错误消息不相关。此外,您提供的代码功能不全,因为它有语法错误。请发布您的实际代码您需要创建一个B
的实例,然后才能调用此类的方法(使用静态或类方法的除外)您可以发布一个示例来演示此问题吗?您拥有的代码无效。这很可能是你正在做的一个小调整。类似于classB.multitypeople()
的方法不起作用,因为该方法需要类实例。但我们无法确定,除非您看起来是在没有实例的情况下直接调用类方法。你为什么要叫那家伙?你这么做想解决什么问题?在这种情况下,您希望self
绑定到什么?
class A():
def __init__(self):
b = B()
b.non_static()
B.multiplyPeople()
class B():
@staticmethod
def multiplyPeople():
print "this was called"
def non_static(self):
print self, " was called"
if __name__ == "__main__":
a = A()
<__main__.B instance at 0x7f3d2ab5d710> was called
this was called