这篇文章主要围绕DefaultArgumentsinPythonFunctions展开,旨在为您提供一份详细的参考资料。我们将全面介绍DefaultArgumentsinPythonFunctions
这篇文章主要围绕Default Arguments in Python Functions展开,旨在为您提供一份详细的参考资料。我们将全面介绍Default Arguments in Python Functions,同时也会为您带来(转)Python 3 collections.defaultdict() 与 dict的使用和区别、AngularJS--[ng:areq] Argument 'xxCtrl' is not a function, got undefined!错误、Argument ''xxx'' is not a function, got undefined,初学、c – std :: function arguments list和typedefs的实用方法。
本文目录一览:- Default Arguments in Python Functions
- (转)Python 3 collections.defaultdict() 与 dict的使用和区别
- AngularJS--[ng:areq] Argument 'xxCtrl' is not a function, got undefined!错误
- Argument ''xxx'' is not a function, got undefined,初学
- c – std :: function arguments list和typedefs
Default Arguments in Python Functions
http://stackabuse.com/default-arguments-in-python-functions/
Functions in Python are used to implement logic that you want to execute repeatedly at different places in your code. You can pass data to these functions via function arguments. In addition to passing arguments to functions via a function call, you can also set default argument values in Python functions. These default values are assigned to function arguments if you do not explicitly pass a parameter value to the given argument. Parameters are the values actually passed to function arguments.
In this article, you will see how to use default arguments in Python functions. But first, we will see how to define a function in Python and how to explicitly pass values to function arguments.
Function without Arguments
Let''s define a very simple Python function without any arguments:
def my_function():
print("This is a function without arguments")
The above script defines a function, my_function
, which doesn''t accept any arguments and simply prints a string.
The following script shows how you''d actually call the my_function()
function:
my_function()
In the output, you should see a simple statement printed to the screen by the my_function()
function:
This is a function without arguments
Function with Explicit Arguments
Let''s now define a simple Python function where we have to pass multiple values for the function arguments. If you do not specify values for all the function arguments, you will see an error.
Here is the function we''ll be using as an example:
def func_args(integer1, integer2):
result = integer1 + integer2
return result
In the code above we create a function, func_args()
, with two arguments integer1
and integer2
. The function adds the values passed in the two arguments and returns the result to the function caller.
Let''s try calling the above function with two arguments:
result = func_args(10, 20)
print(result)
The above script calls the func_args()
method with two parameter values, i.e. 10 and 20. In the output, you should see the sum of these two values, i.e. 30.
Let''s now try to call the func_args()
method without passing values for the arguments:
result = func_args()
print(result)
In the output, you should see the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-3449c8e5e188> in <module>
----> 1 result = func_args()
2 print(result)
TypeError: func_args() missing 2 required positional arguments: ''integer1'' and ''integer2''
The error is quite clear, the function call to func_args()
is missing the 2 required positional arguments, integer1
and integer2
. The error basically tells us that we need to pass values for the integer1
and integer2
arguments via the function call.
Let''s now pass a value for one of the arguments and see what happens:
result = func_args(10)
print(result)
Now in the output, you should again see the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-640ec7b786e1> in <module>
----> 1 result = func_args(10)
2 print(result)
TypeError: func_args() missing 1 required positional argument: ''integer2''
The difference here is that the error now tells us that the value for one of the positional arguments, i.e. integer2
, is missing. This means that without any default argument values set, you have to pass values explicitly for all the function arguments, otherwise an error will be thrown.
What if you want your function to execute with or without the argument values in the function call? This is where default arguments in Python functions come in to play.
Function with Default Arguments
Default arguments in Python functions are those arguments that take default values if no explicit values are passed to these arguments from the function call. Let''s define a function with one default argument.
def find_square(integer1=2):
result = integer1 * integer1
return result
The above script defines a function find_square()
with one default argument i.e. integer1
. The default value for the integer1
argument is set to 2. If you call the find_square()
method with a value for the integer1
argument, the find_square()
function will return the square of that value.
Otherwise, if you do not pass any value for the integer1
argument of the find_square()
function, you will see that the default value, i.e. 2, will be assigned to integer1
, and the function will return the square of 2, i.e. 4.
Let''s first call the find_square()
method with the argument value of 10:
result = find_square(10)
print(result)
Output:
100
When you execute the above script, the value 10 overwrites the default value of 2 for the argument integer1
of the find_square()
function and the function returns 100, which is square of 10.
Now we will call the find_square()
function without any value for the argument1
argument. In this case, you will see that 4 will be returned by find_square()
function since in the absence of the value for the find_square()
function, the default value of 2 will be used as the value for the find_square()
function, as shown below:
result = find_square()
print(result)
Output:
4
A Python function can have multiple default arguments as well. For instance, in the following script, the function adds the integers number passed to the arguments. If none of the integer values is passed to the function, the default arguments would take values 2 and 4 respectively, as shown below:
def add_ints(integer1=2, integer2=4):
result = integer1 + integer2
return result
Let''s first call the add_ints()
function without any parameters:
result = add_ints()
print(result)
Output:
6
Since we did not pass any values for the function arguments, the default argument values, i.e 2 and 4, have been added together.
Let''s now pass two of our own values to the add_ints()
function:
result = add_ints(4, 8)
print(result)
Output:
12
As expected, 4 and 8 were added together to return 12.
A Python function can have both normal (explicit) and default arguments at the same time. Let''s create a function take_power()
. The first argument to the function is a normal argument while the second argument is a default argument with a value of 2. The function returns the result of the value in the first argument raised to the power of value in the second argument.
def take_power(integer1, integer2=2):
result = 1
for i in range(integer2):
result = result * integer1
return result
Let''s first pass only a single argument:
result = take_power(3)
print(result)
Output:
9
In the script above, 3 has been passed as a value to the integer1
argument of the take_power()
function. No value has been provided for the default argument integer2
. Hence, the default value of 2 will be used to take the power of 3 and you will see 9 in the output.
Let''s now pass two values to the take_power()
function.
result = take_power(3, 4)
print(result)
In the output, you will see 3 raised to the fourth power, i.e. 81.
It''s important to note that parameters with default arguments cannot be followed by parameters with no default argument. Take the following function for example:
def take_power(integer1=2, integer2):
result = 1
for i in range(integer2):
result = result * integer1
return result
Trying to call this function will result in an error since the first argument has a default, but the second one does not:
result = take_power(3, 4)
print(result)
Executing this code results in the following error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-640ec7b786e1> in <module>
----> 1 def take_power(integer1=3, integer2):
2 result = 1
SyntaxError: non-default argument follows default argument
(转)Python 3 collections.defaultdict() 与 dict的使用和区别
原文:https://www.cnblogs.com/herbert/archive/2013/01/09/2852843.html
在Python里面有一个模块collections,解释是数据类型容器模块。这里面有一个collections.defaultdict()经常被用到。主要说说这个东西。
综述:
这里的defaultdict(function_factory)构建的是一个类似dictionary的对象,其中keys的值,自行确定赋值,但是values的类型,是function_factory的类实例,而且具有默认值。比如default(int)则创建一个类似dictionary对象,里面任何的values都是int的实例,而且就算是一个不存在的key, d[key] 也有一个默认值,这个默认值是int()的默认值0.
defaultdict
dict subclass that calls a factory function to supply missing values。
这是一个简短的解释
defaultdict属于内建函数dict的一个子类,调用工厂函数提供缺失的值。
比较晕,什么是工厂函数:
来自python 核心编程的解释
Python 2.2 统一了类型和类, 所有的内建类型现在也都是类, 在这基础之上, 原来的
所谓内建转换函数象int(), type(), list() 等等, 现在都成了工厂函数。 也就是说虽然他
们看上去有点象函数, 实质上他们是类。当你调用它们时, 实际上是生成了该类型的一个实
例, 就象工厂生产货物一样。
下面这些大家熟悉的工厂函数在老的Python 版里被称为内建函数:
int(), long(), float(), complex()
str(), unicode(), basestring()
list(), tuple()
type()
以前没有工厂函数的其他类型,现在也都有了工厂函数。除此之外,那些支持新风格的类
的全新的数据类型,也添加了相应的工厂函数。下面列出了这些工厂函数:
dict()
bool()
set(), frozenset()
object()
classmethod()
staticmethod()
super()
property()
file()
再看看它的使用:

import collections
s = [(''yellow'', 1), (''blue'', 2), (''yellow'', 3), (''blue'', 4), (''red'', 1)]
d = collections.defaultdict(list)
for k, v in s:
d[k].append(v)
list(d.items())

这里就开始有点明白了,原来defaultdict可以接受一个内建函数list作为参数。其实呢,list()本身是内建函数,但是再经过更新后,python里面所有东西都是对象,所以list改编成了类,引入list的时候产生一个类的实例。
还是不太明白,再看defaultdict的help解释
- class collections.defaultdict([ default_factory[, ...]])
-
Returns a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.
首先说了,collections.defaultdict会返回一个类似dictionary的对象,注意是类似的对象,不是完全一样的对象。这个defaultdict和dict类,几乎是一样的,除了它重载了一个方法和增加了一个可写的实例变量。(可写的实例变量,我还是没明白)
The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.
defaultdict objects support the following method in addition to the standard dict operations:
- __missing__( key)
-
If the default_factory attribute is None, this raises a KeyError exception with the key as argument.
If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.
-
主要关注这个话,如果default_factory不是None, 这个default_factory将以一个无参数的形式被调用,提供一个默认值给___missing__方法的key。 这个默认值将作为key插入到数据字典里,然后返回。
-
十分晕。有扯出了个__missing__方法,这个__missing__方法是collections.defaultdict()的内建方法。
If calling default_factory raises an exception this exception is propagated unchanged.
This method is called by the __getitem__() method of the dict class when the requested key is not found; whatever it returns or raises is then returned or raised by __getitem__().
Note that __missing__() is not called for any operations besides __getitem__(). This means that get() will, like normal dictionaries, return None as a default rather than using default_factory.
defaultdict objects support the following instance variable:
- default_factory
-
This attribute is used by the __missing__() method; it is initialized from the first argument to the constructor, if present, or to None, if absent.
看样子这个文档是难以看懂了。直接看示例:

import collections
s = [(''yellow'', 1), (''blue'', 2), (''yellow'', 3), (''blue'', 4), (''red'', 1)]
# defaultdict
d = collections.defaultdict(list)
for k, v in s:
d[k].append(v)
# Use dict and setdefault
g = {}
for k, v in s:
g.setdefault(k, []).append(v)
# Use dict
e = {}
for k, v in s:
e[k] = v
##list(d.items())
##list(g.items())
##list(e.items())

看看结果

list(d.items())
[(''blue'', [2, 4]), (''red'', [1]), (''yellow'', [1, 3])]
>>> list(g.items())
[(''blue'', [2, 4]), (''red'', [1]), (''yellow'', [1, 3])]
>>> list(e.items())
[(''blue'', 4), (''red'', 1), (''yellow'', 3)]
>>> d
defaultdict(<class ''list''>, {''blue'': [2, 4], ''red'': [1], ''yellow'': [1, 3]})
>>> g
{''blue'': [2, 4], ''red'': [1], ''yellow'': [1, 3]}
>>> e
{''blue'': 4, ''red'': 1, ''yellow'': 3}
>>> d.items()
dict_items([(''blue'', [2, 4]), (''red'', [1]), (''yellow'', [1, 3])])
>>> d["blue"]
[2, 4]
>>> d.keys()
dict_keys([''blue'', ''red'', ''yellow''])
>>> d.default_factory
<class ''list''>
>>> d.values()
dict_values([[2, 4], [1], [1, 3]])

可以看出
collections.defaultdict(list)使用起来效果和运用dict.setdefault()比较相似
python help上也这么说了
When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault():
说这种方法会和dict.setdefault()等价,但是要更快。
有必要看看dict.setdefault()
- setdefault( key[, default])
-
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
如果这个key已经在dictionary里面存着,返回value.如果key不存在,插入key和一个default value,返回Default. 默认的defaults是None.
但是这里要注意的是defaultdict是和dict.setdefault等价,和下面那个直接赋值是有区别的。从结果里面就可以看到,直接赋值会覆盖。
从最后的d.values还有d[“blue”]来看,后面的使用其实是和dict的用法一样的,唯一不同的就是初始化的问题。defaultdict可以利用工厂函数,给初始keyi带来一个默认值。
这个默认值也许是空的list[] defaultdict(list), 也许是0, defaultdict(int).
再看看下面的这个例子。
defaultdict(int) 这里的d其实是生成了一个默认为0的带key的数据字典。你可以想象成 d[key] = int default (int工厂函数的默认值为0)
d[k]所以可以直接读取 d[“m”] += 1 就是d[“m”] 就是默认值 0+1 = 1
后面的道理就一样了。

>>> s = ''mississippi''
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> list(d.items())
[(''i'', 4), (''p'', 2), (''s'', 4), (''m'', 1)]

AngularJS--[ng:areq] Argument 'xxCtrl' is not a function, got undefined!错误
在angular中文社区群中,有时会听见某些同学问关于”ng:areq“的错误:
[ng:areq] Argument ''DemoCtrl'' is not a function,got undefined!
这往往是因为忘记定义controller或者是声明了多次module,多次声明module会导致前边的module定义信息被清空,所以程序就会找不到已定义的组件。这我们也能从angular源码中了解到(来自loader.js):
function setupModuleLoader(window) { ... function ensure(obj,name,factory) { return obj[name] || (obj[name] = factory()); } var angular = ensure(window,''angular'',Object); return ensure(angular,''module'',function() { var modules = {}; return function module(name,requires,configFn) { var assertNotHasOwnProperty = function(name,context) { if (name === ''hasOwnProperty'') { throw ngminerr(''badname'',''hasOwnProperty is not a valid {0} name'',context); } }; assertNotHasOwnProperty(name,''module''); if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules,function() { if (!requires) { throw $injectorminerr(''nomod'',"Module ''{0}'' is not available! You either misspelled " + "the module name or forgot to load it. If registering a module ensure that you " + "specify the dependencies as the second argument.",name); } var invokeQueue = []; var runBlocks = []; var config = invokelater(''$injector'',''invoke''); var moduleInstance = { _invokeQueue: invokeQueue,_runBlocks: runBlocks,requires: requires,name: name,provider: invokelater(''$provide'',''provider''),factory: invokelater(''$provide'',''factory''),service: invokelater(''$provide'',''service''),value: invokelater(''$provide'',''value''),constant: invokelater(''$provide'',''constant'',''unshift''),animation: invokelater(''$animateProvider'',''register''),filter: invokelater(''$filterProvider'',controller: invokelater(''$controllerProvider'',directive: invokelater(''$compileProvider'',''directive''),config: config,run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; function invokelater(provider,method,insertMethod) { return function() { invokeQueue[insertMethod || ''push'']([provider,arguments]); return moduleInstance; }; } }); }; }); }
在代码中,我们能了解到angular在启动时,会设置全局的angular对象,然后在angular对象上发布module这个API。关于module API代码,能清晰的看见第一行谓语句,module名称不能以hasOwnProperty命名,否则会抛出”badname“的错误信息。紧接着,如果传入了name参数,其表示是声明module,则会删除已有的module信息,将其置为null。
从moduleInstance的定义,我们能够看出,angular.module为我们公开的API有:invokeQueue、runBlocks、requires、name、provider、factory、servic、value、constant、animation、filter、controller、directive、config、run。其中invokeQueue和runBlocks是按名约定的私有属性,请不要随意使用,其他API都是我们常用的angular组件定义方法,从invokelater代码中能看到这类angular组件定义的返回依然是moduleInstance实例,这就形成了流畅API,推荐使用链式定义这些组件,而不是声明一个全局的module变量。
最后,如果传入了第三个参数configFn,则会将它配置到config信息中,当angular进入config阶段时,它们将会依次执行,进行对angular应用或者angular组件如service等的实例化前的配置。
Argument ''xxx'' is not a function, got undefined,初学
我们一般接触到的第一个入门教程都是类似与这样的,代码简单。我们有个ng-app作为Angular的启动口,然后ng-controller="helloCtrl"控制p标签。View层,则用双花括号出入数据greeting的message值。然后在下面的script定义了一个helloCtrl的函数,并为$scope.greeting赋了值。这一切看起来都是那么自然,想象中,浏览器就该出现,"Hello, World!"。可惜的是,浏览器给了我们这样的回复。
没错,这就是开头所说的那个。于是我弄不懂,为什么老师可以跑通,我却跑不通,大家都是Angular-1.3.0。国内不给力,很难找到答案,最后去StackOverflow找到了。因为从Angular-1.3.0 beta15开始,Angular不再支持全局的Controller!那么问题来了,如何在Angular里定义模块呢?
当然这篇blog是为了让大家学习Angular的时候别遇到闭门羹,我大致说一下。AngularJs里,有一个angular.module,模块机制就是靠这个来加载的。我们来看看如何可以重新出现梦寐以求的“Hello World”。
我们看看,改了什么,ng-app="myApp"首先给入口赋了名字,然后再下面进行模块的初始化。在angular.module(String, moduleArray)函数里,第一个String参数是该模块的名字,第二个参数是所依赖的模块(这里暂时用不着),返回了myApp这个模块,然后再通过模块的controller方法定义helloCtrl控制器即可。
当然我们要解释依赖模块的话,我们可以看一下稍作修改的第三版Demo
仅仅是多定义一个helloController模块,这样myApp,就可以仅仅作为启动口,而不会混杂着控制器。我们可以定义多个js文件,清晰明确的通过模块梳理整个项目的结构。
转自:http://www.cnblogs.com/YikaJ/p/4226313.html
c – std :: function arguments list和typedefs
typedef std::function<int arg1,float arg2> MyFunction;
在我的代码中的某处使用它:
MyFunction func = [](int arg1,float arg2){ /* do someting */ };
问题是每次我更改函数的参数数量(例如我添加第三个参数char arg3) – 我被迫在我的代码中使用MyFunction更新它(即使这些参数不是一点也没用过.
而且我懒得那样做.有没有办法从它的类型获取std :: function的参数列表? (我的意思是)所以函数创建看起来像那样?:
MyFunction func = [](MyFunction::args){ /* do someting */ };
解决方法
MyFunction func = [](int arg1,float arg2,auto&&... unused){ /* ... */ };
这将转换为std :: function< Sig>对于任何以int开头的签名,浮点数.
今天关于Default Arguments in Python Functions的分享就到这里,希望大家有所收获,若想了解更多关于(转)Python 3 collections.defaultdict() 与 dict的使用和区别、AngularJS--[ng:areq] Argument 'xxCtrl' is not a function, got undefined!错误、Argument ''xxx'' is not a function, got undefined,初学、c – std :: function arguments list和typedefs等相关知识,可以在本站进行查询。
本文标签: