考虑三个功能:
def my_func1():
print "Hello World"
return None
def my_func2():
print "Hello World"
return
def my_func3():
print "Hello World"
Run Code Online (Sandbox Code Playgroud)
他们似乎都返回无.这些函数的返回值如何表现有什么不同?是否有任何理由更喜欢一个与另一个?
Python函数可以作为另一个函数的参数吗?
说:
def myfunc(anotherfunc, extraArgs):
# run anotherfunc and also pass the values from extraArgs to it
pass
Run Code Online (Sandbox Code Playgroud)
所以这基本上是两个问题:
BTW,extraArgs是anotherfunc参数的列表/元组.
鉴于此示例函数:
def writeFile(listLine,fileName):
'''put a list of str-line into a file named fileName'''
with open(fileName,'a',encoding = 'utf-8') as f:
for line in listLine:
f.writelines(line+'\r\n')
return True
Run Code Online (Sandbox Code Playgroud)
这个return True陈述有用吗?
它和没有它有什么区别?如果没有返回功能会发生什么?
生成器只是一个函数,它返回一个可以在其上调用的对象,这样每次调用它都会返回一些值,直到它引发一个StopIteration异常,表示已生成所有值.这样的对象称为迭代器.
>>> def myGen(n):
... yield n
... yield n + 1
...
>>> g = myGen(6)
Run Code Online (Sandbox Code Playgroud)
我从Python中理解生成器中引用了这个?
这是我想弄清楚的:
哪个是发电机?myGen还是myGen(6)?
根据上面提到的报价,我认为发电机应该是myGen.并且myGen(6)是返回的迭代器对象.但我真的不确定.
当我尝试这个时:
>>> type(myGen)
<type 'function'>
>>> type(g) # <1>this is confusing me.
<type 'generator'>
>>> callable(g) # <2> g is not callable.
False
>>> callable(myGen)
True
>>> g is iter(g) # <3> so g should an iterable and an iterator
True # at the same time. And it …Run Code Online (Sandbox Code Playgroud)我一直在学习python大约一周,下面是问题:
码
def Foo():
pass
def Bar():
return None
Run Code Online (Sandbox Code Playgroud)
用法
a = Foo()
print(a)
# None
b = Bar()
print(b)
# None
Run Code Online (Sandbox Code Playgroud)
问题:1.当我们已经返回时,为什么我们需要通过?是否有一些情况,返回无法处理但传递可以?
如果您的问题作为此问题的重复项而被关闭,那是因为您有一些通用形式的代码
x = X()
# later...
x = x.y()
# or:
x.y().z()
Run Code Online (Sandbox Code Playgroud)
其中X是某种类型,它提供了y旨在z变异(修改)对象(X类型的实例)的方法。这可以适用于:
list、dict和setbytearray这种形式的代码很常见,但并不总是错误的。问题的明显迹象是:
与x.y().z()一样,会引发异常AttributeError: 'NoneType' object has no attribute 'z'。
有了x = x.y(),x就变成None, 而不是被修改的对象。这可能会被后来的错误结果发现,或者被像上面这样的异常(x.z()稍后尝试时)发现。
Stack Overflow 上有大量关于这个问题的现有问题,所有这些问题实际上都是同一个问题。之前甚至有多次尝试在特定上下文中涵盖同一问题的规范。然而,理解问题并不需要上下文,因此这里尝试一般性地回答:
代码有什么问题吗?为什么这些方法会这样,我们如何解决这个问题?
另请注意,当尝试使用 alambda(或列表理解)来产生副作用时,会出现类似的问题。
同样明显的问题可能是由因其他原因返回的方法引起的None …
Python 2.7.以下函数返回True或False.我正在尝试打印此结果.现在我知道我可以用"print"替换"return",但我不想在函数内打印.
def OR_Gate():
a = raw_input("Input A:")
b = raw_input("Input B:")
if a == True or b == True:
return True
if a == False and b == False:
return False
print OR_Gate()
Run Code Online (Sandbox Code Playgroud)
当我运行下面的代码时,我被提示输入a和b的值,然后输出为"None",而不是True或False.如何打印函数OR_Gate的返回值?
所以我正在制作一个递归函数的图表来围绕递归,我注意到显然每个函数最后都执行 return ?
另一个问题,函数究竟返回什么?传递给它的所有参数(假设有多个参数)?或者某种价值?
(t 只是一个执行实际绘图的实体)
def koch(t, n):
"""Draws a koch curve with length n."""
if n<30:
fd(t, n)
return
m = n/3.0
koch(t, m)
lt(t, 60)
koch(t, m)
rt(t, 120)
koch(t, m)
lt(t, 60)
koch(t, m)
Run Code Online (Sandbox Code Playgroud)