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

蛋糕

我有两个类 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):

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

从Python 2.7中的另一个类方法调用一个类方法

如何从另一个类中迅速调用另一个方法?

如何在另一个类中调用一个类的main()方法?

如何从Android中的另一个片段类调用一个片段的方法

如何从另一个 python 文件中的一个 python 文件中的类调用方法

Python 3-调用方法以更改类中的另一个方法

在python的同一类中的另一个方法中调用一个类的方法

如何在同一个类的另一个方法中调用一个方法?

如何在同一个类中的另一个 api 中调用 python api 方法?

如何从另一个类方法调用一个类方法

Python-如何从另一个新修改的python文件中调用类方法

在Ruby的另一个类中的一个类中调用方法

如何在一个类中从另一个调用一个函数(方法)?

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

如何从另一个类调用HashMap的方法?

如何从另一个类调用 invalidate() 方法?

如何从另一个类调用方法?

Flutter:如何从另一个类调用方法?

如何从另一个项目调用类的方法

如何从另一个小写的类调用方法?

如何从另一个类调用@selector方法

如何从另一个类调用get方法?

如何从另一个类调用void方法

从Python的另一个类内部调用方法

python,从另一个类调用方法

Repaint()方法在另一个类中调用

从UIButton中的另一个类调用方法

在PHP的另一个类中调用方法

如何从一个类调用方法到另一个类