[Tutor] How can I have type "function" in my script?
Alan Gauld
alan.gauld at btinternet.com
Tue May 8 01:24:22 CEST 2012
On 07/05/12 21:37, xancorreu wrote:
> This is the code:
OK, But it's not clear from that why you want the type.
You are not doing anything meaningful with the type.
> class Tag:
>
> def __init__(self, nom, tipus, valor):
> self.nom = nom
> self.tipus = tipus
> self.valor = valor
>
> def __str__(self):
> return "Nom: " + str(self.nom) + ", Tipus: " + str(self.tipus) + ",
> Valor: " + str(self.valor)
You store it then print the string version of it.
Why not just pass a string name?
> def main():
> a = Tag("descripciĆ³", str, "primera tasca")
> b = Tag("unmes", str, lambda x: x+1)
> c = Tag("twice", type(lambda: x: x), lambda x: 2*x)
> and it fails here:
>
> $ python3 tasques.py
> File "tasques.py", line 26
> c = Tag("twice", type(lambda: x: x), lambda x: 2*x)
> ^
> SyntaxError: invalid syntax
As it says there is a syntax error. Look at your two lambda expressions,
the second one has an extra :
If you really want the type of a function just use one of the
built in functions... or a very simple lambda:
>>> type(pow)
<type 'builtin_function_or_method'>
>>> type(lambda : 0)
<type 'function'>
>>>
But in most cases you don't need the type and the callable() function is
more useful.
>>> callable(pow)
True
>>> callable(lambda : 0)
True
>>> callable(7)
False
>>>
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list