Skip to content Skip to sidebar Skip to footer

How To Call A Class Method In Another Method In Python?

I am trying to print 'okay, thanks'. When I run it on shell, it prints on separate line and the 'thanks' is printing before 'okay'. Can anyone help what I am doing wrong? >>&

Solution 1:

Your problem is that when you call test.a(), you print a string, not return it. Change your code do this and it'll work just fine:

defa(self):
     return'thanks'

By what you said in your question, it doesn't seem like you need to use the end keyword argument to print. Just pass test.a() as another argument:

print('okay,', test.a())

Solution 2:

print evaluates the functions in order before processing the resulting expressions.

def a(): print('a')
def b(): print('b')
def c(): print('c')

print(a(), b())
print('a', b())
print ('a', b(), c())
print (a(), 'b', c())

Outputs:

a
b
(None, None)
b
('a', None)
b
c
('a', None, None)
a
c
(None, 'b', None)

So, python is evaluating the tuple before passing it over to print. In evaluating it, the method 'a' gets called, resulting in 'thanks' being printed.

Then print statement in b proceeds, which results in 'okay' being printed.

Solution 3:

To print 'okay thanks' your One.a() should return a string rather than a print statement alone.

Also not sure what's the "test" parameter in Two.b is for, since you overwrite it to be an instance of class One immediately.

classOne:defa(self):
        return' thanks'classTwo:defb(self):
        test = One()
        print('okay', end = test.a())

>>>> test1 = Two()
>>>> test1.b()
okay thanks
>>>>

Solution 4:

I'd try something like this as it means you don't have to change class One. This reduces the amount of classes you have to change, which isolates the change and the scope for error; and maintains the behaviour of class One

classOne:defa(self):
         print('thanks')

classTwo:defb(self, test):
         test = One()
         print('okay', end=' ')
         test.a()

Post a Comment for "How To Call A Class Method In Another Method In Python?"