为什么“返回自我"返回无? [英] Why does 'return self' return None?
本文介绍了为什么“返回自我"返回无?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 getTopParent()
中获取链的顶部节点.当我打印出self.name
时,它确实打印出父实例的名称;但是,当我返回 self
时,它返回 None.这是为什么?
I'm trying to get the top node of a chain in getTopParent()
. When I print out self.name
, it indeed prints out the name of the parent instance; however, when I return self
, it returns None. Why is this?
class A:
def __init__( self, name ):
self.name = name
self.owner = None
def setChild( self, l ):
l.owner = self
def getTopParent( self ):
if( self.owner == None ): # None == top parent
print( "Got top: %s" % self.name )
return self
else:
print( "checking %s" % self.name )
self.owner.getTopParent()
a = A( "parent" )
b = A( "child1" )
c = A( "child2" )
d = A( "child3" )
a.setChild( b )
b.setChild( c )
c.setChild( d )
print( d.getTopParent() )
>>> checking child3
checking child2
checking child1
Got top: parent
None
推荐答案
你需要返回 self.owner.getTopParent()
!
在 Python 中,您必须实际使用 return
语句从函数返回某些内容,否则返回 None
.
In Python, you must actually use the return
statement to return something from a function, otherwise None
is returned.
这篇关于为什么“返回自我"返回无?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文