指定函数的参数类型 [英] Specifing arguments type for a function
问题描述
我有一个功能
def f(the_arg):
....
和我想声明the_arg必须只是某种类型
(实际上是一个列表)。有办法吗?
Thnx
PAolo
-
如果您有一分钟的时间可以访问我的photogrphy网站:
http:// mypic .co.nr
I have a function
def f(the_arg):
....
and I want to state that the_arg must be only of a certain type
(actually a list). Is there a way to do that?
Thnx
PAolo
--
if you have a minute to spend please visit my photogrphy site:
http://mypic.co.nr
推荐答案
Paolo Pantaleo写道:
Paolo Pantaleo wrote:
我有一个功能
def f(the_arg):
...
我想声明the_arg必须只是某种类型
(实际上是一个清单) )。有没有办法做到这一点?
I have a function
def f(the_arg):
...
and I want to state that the_arg must be only of a certain type
(actually a list). Is there a way to do that?
是和否。您可以通过调用例如
def f(arg)来确保传递的对象是一个列表:
如果不是isinstance(arg,list):
加注不是列表!
或者,您可以将它作为可迭代使用 - 而例外将是
来自arg不可迭代。
但你不能做的就是让python抱怨这个:
def f(arg):
for e in arg:
print e
f(100)
在实际调用f之前。它总是在运行时失败。
Diez
Yes and no. You can ensure that the passed object is a list, by calling e.g.
def f(arg):
if not isinstance(arg, list):
raise "Not a list!"
Alternatively, you can just use it as an iterable - and the exception will
come from arg not being iterable.
But what you can''t do is make python complain about this:
def f(arg):
for e in arg:
print e
f(100)
before actually calling f. It will always fail at runtime.
Diez
> Paolo Pantaleo写道:
> Paolo Pantaleo wrote:
我有一个函数
def f(the_arg):
...
我想声明the_arg必须只是某种类型
(实际上是一个列表)。有没有办法做到这一点?
I have a function
def f(the_arg):
...
and I want to state that the_arg must be only of a certain type
(actually a list). Is there a way to do that?
是和否。您可以通过调用例如
def f(arg)来确保传递的对象是一个列表:
如果不是isinstance(arg,list):
raise" Not a list!"
或者,您可以将它作为一个可迭代使用 - 而例外将来自arg不可迭代。
但你能做什么要做的就是让python抱怨这个:
def f(arg):
对于e in arg:
打印e
f(100在实际调用f之前。
它总是在运行时失败。
Diez
Yes and no. You can ensure that the passed object is a list, by calling e.g.
def f(arg):
if not isinstance(arg, list):
raise "Not a list!"
Alternatively, you can just use it as an iterable - and the exception will
come from arg not being iterable.
But what you can''t do is make python complain about this:
def f(arg):
for e in arg:
print e
f(100)
before actually calling f. It will always fail at runtime.
Diez
怎么样
def f(arg):
如果输入(arg)==''list'':
#do something
-
---
Rony Steelandt
BuCodi
rony dot steelandt(at)bucodi dot com
访问python博客,网址为: http://360.yahoo.com/bucodi
>那么
def f(arg):
如果输入(arg)==''list'':
#do something
def f(arg):
if type(arg)==''list'':
#do something
有几件事:
- list是代码中的一个字符串 - 它不起作用:
Several things:
- list is a string in your code - which wont work:
type([])==''list''
False
它需要是没有引号的列表。
- 你不会得到列表的子类:
class Foo(list):
.... pass
....类型(Foo())== list
type([]) == ''list'' False
It needs to be list w/o quotes.
- you won''t get sublclasses of list:
class Foo(list): .... pass
.... type(Foo()) == list
False
好用正如我已经提到过的那样。
Diez
False
So better use isinstance, as I already mentioned.
Diez
这篇关于指定函数的参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!