如何在python中的另一个方法中调用类方法?
我正在打印“好的,谢谢”。当我在shell上运行它时,它在单独的行上打印,“谢谢”在“好”之前打印。谁能帮我做错事吗如何在python中的另一个方法中调用类方法?,python,class,methods,Python,Class,Methods,我正在打印“好的,谢谢”。当我在shell上运行它时,它在单独的行上打印,“谢谢”在“好”之前打印。谁能帮我做错事吗 >>> test1 = Two() >>> test1.b('abcd') >>> thanks >>> okay 我的代码 class One: def a(self): print('thanks') class Two: def b(self, test)
>>> test1 = Two()
>>> test1.b('abcd')
>>> thanks
>>> okay
我的代码
class One:
def a(self):
print('thanks')
class Two:
def b(self, test):
test = One()
print('okay', end = test.a())
print
在处理结果表达式之前,按顺序计算函数
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())
产出:
a
b
(None, None)
b
('a', None)
b
c
('a', None, None)
a
c
(None, 'b', None)
因此,python在将元组传递给打印之前对其进行评估。在对其进行评估时,会调用方法“a”,从而打印出“谢谢”
然后在
b
中继续打印语句,这会导致打印“OK”。您的问题是,当您调用test.a()
时,您打印一个字符串,而不是返回它。更改代码执行此操作,它将正常工作:
def a(self):
return 'thanks'
根据您在问题中所说的,您似乎不需要使用end
关键字参数来print
。只需通过test.a()
作为另一个参数:
print('okay,', test.a())
要打印“好的,谢谢”,您的One.a()应该返回字符串,而不仅仅是打印语句 也不确定Two.b中的“test”参数是用于什么的,因为您会立即将其覆盖为类1的实例
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
>>>>
我想试试这样,因为这意味着你不必换一班。这减少了必须更改的类的数量,从而隔离了更改和错误范围;并保持一班的行为
class One:
def a(self):
print('thanks')
class Two:
def b(self, test):
test = One()
print('okay', end=' ')
test.a()