超级函数返回 None 和结果
super function is returning None along with result
我有以下代码与父 class Test
和 subclass MyTest
。
从外部,我试图访问父 class 而不是子 class 的方法。所以我期待父 class 的 display
函数。
所以,我使用 super
函数来实现这一点。到目前为止,一切都很好。但是当我尝试将超级函数的 return 分配给一个变量时,比如 z
,我看到它打印出我期望的内容,还打印出 'None'
.
class Test(object):
def display(self, x):
self.x = x
print self.x
class MyTest(Test):
def someother(self):
print "i am a different method"
def display(self, x):
self.x = x
print "Getting called form MyTest"
a = MyTest()
z = super(type(a), a).display(10)
print z
10
None
我试图理解为什么超级函数 returning 'None' 以及预期值
python 中任何未明确使用 return
的 callable 默认情况下将 return None
.
所以,要解决这个问题,只需使用 return
而不是打印:
class Test(object):
def display(self, x):
self.x = x
return self.x
您的 MyTest.display
方法不包含任何 return
语句。
因此,隐含 return None
。
因此,z = super(type(a), a).display(10)
导致将 None
分配给 z
。
您需要在您的方法中附加一个return
语句,例如:
def display(self, x):
self.x = x
print "Getting called form MyTest"
return self.x
我有以下代码与父 class Test
和 subclass MyTest
。
从外部,我试图访问父 class 而不是子 class 的方法。所以我期待父 class 的 display
函数。
所以,我使用 super
函数来实现这一点。到目前为止,一切都很好。但是当我尝试将超级函数的 return 分配给一个变量时,比如 z
,我看到它打印出我期望的内容,还打印出 'None'
.
class Test(object):
def display(self, x):
self.x = x
print self.x
class MyTest(Test):
def someother(self):
print "i am a different method"
def display(self, x):
self.x = x
print "Getting called form MyTest"
a = MyTest()
z = super(type(a), a).display(10)
print z
10
None
我试图理解为什么超级函数 returning 'None' 以及预期值
python 中任何未明确使用 return
的 callable 默认情况下将 return None
.
所以,要解决这个问题,只需使用 return
而不是打印:
class Test(object):
def display(self, x):
self.x = x
return self.x
您的 MyTest.display
方法不包含任何 return
语句。
因此,隐含 return None
。
因此,z = super(type(a), a).display(10)
导致将 None
分配给 z
。
您需要在您的方法中附加一个return
语句,例如:
def display(self, x):
self.x = x
print "Getting called form MyTest"
return self.x