python 如何获得返回值 return
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 如何获得返回值 return相关的知识,希望对你有一定的参考价值。
class AA():
def __init__(self):
self.test()
def test(self):
'''xxxxxxxxxxx
'''
return "This is a test"
a=AA()
只有a.test()后才有返回值,但是我初始化后test里有运算,请问初始化后为什么没有返回值的?该怎么写才在初始化后就能得到返回值,而不是再调用它的方法。
前面两位的方法其实和先初始化AA,在调用AA的test()效果是一样的,在初始化AA()的时候,调用的那次test()的返回值已经丢了,比如这样定义:
class AA():def __init__(self):
self.count=0
self.test()
def test(self):
""" test function"""
self.count +=1
return str(self.count)
def __str__(self):
return self.test()
def funcAA():
return AA().test()
然后测试,会发现,str(AA())和funcAA()的返回值都是2
要得到在初始化过程中的返回值,可以用变量把结果保存起来,比如:
class BB():def __init__(self):
self.count=0
self.result=self.test()
def test(self):
self.count += 1
return str(self.count)
然后b=BB()后,b.result的返回值是1.
至于多个返回的问题,还好python是弱类型的,可以这样:
class CC():def __init__(self, count):
self.count=count
self.result=self.test()
def test(self):
self.count += 1
if self.count % 2 == 0:
return self.count
else:
return "hello world"
结果如下:
AA()返回的是AA构造出来的实例。你不定义类,直接定义test函数就可以直接返回了。或者你可以:
class AA():def __init__(self):
self.test()
def test(self):
'''xxxxxxxxxxx
'''
return "This is a test"
def funcAA():
return AA().test()
这样你直接funcAA()就可以了。
参考技术B 初始化里加一个属性吧。感觉这样最简单,我也是菜鸟一枚,看看这样行不行class AA():
def __init__(self,):
self.b=self.test()
def test(self):
'''xxxxxxxxxxx '''
return "this is a test"
a=AA()
print a.test()
print a.b
>>> ================================ RESTART ================================
>>>
this is a test
this is a test
>>> 参考技术C 嗯。加一个函数就可以,改成下面这样子
class AA():
def __init__(self):
self.test()
def test(self):
'''xxxxxxxxxxx
'''
return "This is a test"
def __str__(self):
return self.test()
a=str(AA())
这样可以。
每个函数返回,如果你不使用,它就会消失在内存里。被回收。所以你的__init__函数虽然也调 用了test(),但是返回值只是没有使用它。追问
如果多个返回值怎么返回,多个返回值还不能一起返回,当我返回A就返回A,想返回B就返回B.貌似不能用俩个 __str__
追答你的问题难倒我了。真不知道怎么用这种方式实现。可能需要换一个方式吧。
通常的用法是这样
a=AA()
a.get_a()
a.get_b()
def __call__(self):
return self.test()
def test(self):
return 'xxxx'
如何使用Python中的subprocess.Popen返回编码值?
有人可以告诉我如何编码return语句,以便它可以解码它。或者需要更改以获得编码值。
码
def run_process(cmd_args):
with subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
return proc.communicate()
res = run_process(cmd_args);
print(res)
print(res.decode("utf-8"))
产量
print(res.decode("utf-8"))
AttributeError: 'tuple' object has no attribute 'decode'
Popen.communicate
返回(stdout, stderr)
的元组,因此您需要将返回值视为:
stdout, stderr = run_process(cmd_args);
print(stdout)
print(stdout.decode("utf-8"))
请阅读Popen.communicate
's documentation了解更多详情。
以上是关于python 如何获得返回值 return的主要内容,如果未能解决你的问题,请参考以下文章