2017-11-20 5 views
-1

Ich habe zwei Klassen A und B, ich möchte eine Methode von Klasse A in Klasse B ausführen. Ich schrieb den Code, aber es funktioniert nicht, ich bekomme Folgendes Fehler:Python3 So rufen Sie eine Methode aus einer Klasse in einer anderen Klasse

AttributeError: 'B' object has no attribute 'testPrint'

Meine Klassen:

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 

Führen Sie das Programm

b = B() 
b.b1() 
+0

Versuchen:. 'F = A() test_1()' –

+0

@MauriceMeyer dann gibt es die Fehlermeldung: Typeerror: test_1() fehlt 1 erforderliche Positions Argument : 'self' – Kaker

+0

Was ist deine eigentliche Frage? Verstehst du, warum du 'AttributError' bekommst? – Goyo

Antwort

1

Sie benötigen Klasse A instanziieren:

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) 

Returns (Python3):

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

danke viel gut funktioniert – Kaker

Verwandte Themen