How to call a class method in another method in python?

蓝咒 提交于 2019-12-11 10:19:26

问题


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?

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

My code

class One:
     def a(self):
         print('thanks')

class Two:
     def b(self, test):
         test = One()
         print('okay', end = test.a())

回答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:

 def a(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())



回答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.




回答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.

class One:
    def a(self):
        return ' thanks'

class Two:
    def b(self):
        test = One()
        print('okay', end = test.a())

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



回答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

class One:
     def a(self):
         print('thanks')

class Two:
     def b(self, test):
         test = One()
         print('okay', end=' ')
         test.a()


来源:https://stackoverflow.com/questions/14391828/how-to-call-a-class-method-in-another-method-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!