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"

结果如下:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-07-04

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()就可以了。

第2个回答  2013-07-04
初始化里加一个属性吧。感觉这样最简单,我也是菜鸟一枚,看看这样行不行
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
>>>
第3个回答  2013-07-04
嗯。加一个函数就可以,改成下面这样子
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()

第4个回答  2013-07-04
class AA():
def __call__(self):
return self.test()
def test(self):
return 'xxxx'
相似回答