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

2024-06-06 18:41:59 发布

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

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

AttributeError: 'B' object has no attribute '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()

Tags: 方法代码testselfreturnobjectinitdef
1条回答
网友
1楼 · 发布于 2024-06-06 18:41:59

您需要实例化类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):

wywolanie funkcji z klasy b
Function test_1 in class A: 
testPrint:1

相关问题 更多 >