Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3如何从一个类调用另一个类中的方法_Python - Fatal编程技术网

Python3如何从一个类调用另一个类中的方法

Python3如何从一个类调用另一个类中的方法,python,Python,我有两个类A和B,我想从类B中的类A运行一个方法。我编写了代码,但它不工作,我得到以下错误: AttributeError:“B”对象没有属性“testPrint” 我的班级: class A: def __init__(self): self.v = 'A' def test_1(self): i = 1 print('Function test_1 in class A: ') x = self.testPri

我有两个类A和B,我想从类B中的类A运行一个方法。我编写了代码,但它不工作,我得到以下错误:

AttributeError:“B”对象没有属性“testPrint”

我的班级:

class A:
    def __init__(self):
        self.v = 'A'

    def test_1(self):
        i = 1
        print('Function test_1 in class A: ')
        x = self.testPrint(i) # i think error is here
        return x

    def testPrint(self, i):
        return 'testPrint: '+i

class B:
    def __init__(self):
        self.v = 'B'

    def b1(self):
        print('wywolanie funkcji z klasy b')
        f = A.test_1(self)
        return f
运行程序

b = B()
b.b1()

您需要实例化类别A:

class A:
    def __init__(self):
        self.v = 'A'

    def test_1(self):
        i = 1
        print('Function test_1 in class A: ')
        x = self.testPrint(i) # i think error is here
        return x

    def testPrint(self, i):
        return 'testPrint: %s' % i

class B:
    def __init__(self):
        self.v = 'B'

    def b1(self):
        print('wywolanie funkcji z klasy b')
        f = A().test_1()
        return f


b = B()
res = b.b1()
print (res)
返回(Python3):


Try:
f=A().test_1()
@MauriceMeyer然后出现错误:TypeError:test_1()缺少1个必需的位置参数:“self”您的实际问题是什么?你明白为什么你会得到
AttributeError
wywolanie funkcji z klasy b
Function test_1 in class A: 
testPrint:1