【问题标题】:Passing argument between two classes在两个类之间传递参数
【发布时间】:2016-02-09 05:46:31
【问题描述】:

我有一个具有这种结构的 python 程序:

import sys

class A:
    def __init__(self):
        ...

    def func(self, other, args):
        z = something
        n = B.start(z)
        print n

    def other_funcs(self, some, args):
        ...

class B:
    def __init__(self):
         self.start(z)

    def start(self, z)
         k = something
         return k

if __name__ == '__main__'
    A()

当我生成z 时,我想将它提供给 B 类,然后 B 再次为我返回 k。

但错误存在:

TypeError: unbound method start() must be called with B instance as first argument (got list instance instead)

【问题讨论】:

  • 不应该self.start(z)z 没有定义吗?

标签: python class oop


【解决方案1】:

您也可以初始化一个B 对象:

n = B().start(z)

但是,您的 __init__ 方法使用参数 z 调用 start 可能无法正常工作,因为尚未定义 z

【讨论】:

  • 现在错误是:NameError: global name 'B' is not defined
  • 在源码中切换B类和A类的位置(B必须在A之前定义)
  • 我又犯了那个错误。我不应该导入一些东西吗?
  • 你不需要导入任何东西,因为两个类都定义在同一个模块中(即同一个 .py 文件)
  • 请用你的新代码更新你的问题,新的错误信息包括完整的堆栈跟踪;或发布另一个问题。
【解决方案2】:

IIUC,您在这里寻找的是classmethod

问题是您没有B 对象,而只有B 类。你需要一个B 的方法,它接受一个类,而不是一个实例。像这样定义start

@classmethod
def start(cls, z):

例如,这运行良好:

class A:                                                                                                                                                                                               
     def func(self):                                                          
          n = B.start(0)                                                          


class B:    
     @classmethod                                                                                                                                               
     def start(cls, z):                                                          
          pass                                                                 

if __name__ == '__main__':                                                   
     A().func()          

【讨论】:

  • 现在的错误是:NameError: global name 'B' is not defined
  • @MLSC 以上对我来说运行良好。顺便说一句,很明显您发布的代码并不完全是您正在使用的代码,因为它还有其他错误(例如,缺少:)。
  • 您的缩进已关闭
【解决方案3】:

您可以修改 B 类的 __init__ 以获取将 z 传递给它的参数。

class B:
    __init__(self, z): #Pass 'z' when you create an object a 'class B' in 'class A'

您的代码存在一些问题。

您需要了解constructor 是什么以及何时调用它。你有

if __name__ == '__main__': # Fixed missing colon here
    A()

这只会调用class A__init__函数。

你需要使用类似的东西

A().func() # Pass required arguments here 

在类中使用方法的正确方法是创建对象(但类方法不需要)。在你的class A 你有

n = B.start(z) # Line in func() of class A

这不起作用。

您需要在class B 中使用__init__ 所需的参数调用B(),而不仅仅是B

class A 传递消息并从class B 打印的示例代码:

class foo:
    def __init__(self):
        self.var1 = "I'm from class A"
        bar(self.var1)


class bar:
    def __init__(self, var):
        print(var)

if __name__ == '__main__':
    foo()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多