I have what may be a dopey question about Python's date function.
Let's say I want to pass the script a date, July 2nd 2013. This code works fine:
from datetime import date
july_2nd = date(2013,7,2)
print july_2nd
Output:
2013-07-02
So now what if I want to pass the date() function a value stored in a variable, which I can set with a function, rather than hard coding 7/2/13, so I try this and get an error:
from datetime import date
july_2nd = (2013,7,2)
print date(july_2nd)
Error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
Can anyone explain what's going on here?
You want to pass in the tuple as separate arguments, using the *args splat syntax:
date(*july_2nd)
By prefixing july_2nd with an asterisk, you are telling Python to call date() with all values from that variable as separate parameters.
See the calls expression documentation for details; there is a **kwargs form as well to expand mapping into keyword arguments.
Related
so i'm trying to learn about classes in python but for some reason i can't get Wiek function working.
i get the error:
Traceback (most recent call last):
File "D:/pythonProject/MEDIUM.py", line 36, in <module>
fafik.Wiek()
TypeError: 'int' object is not callable
class Pies(Ssaki):
def __init__(self, LiczbaKonczynPsa, ImiePsa, WiekPsa):
self.LiczbaKonczyn = LiczbaKonczynPsa
self.Wiek = WiekPsa
self.Imie = ImiePsa
def Przedstaw(self):
print('Ten pies wabi się: ', self.Imie)
def Konczyny(self):
print('Ten pies posiada ', self.LiczbaKonczyn, 'kończyny')
def Wiek(self):
print('Wiek psa wynosi 6')
fafik = Pies(4, 'BOBO', WiekPsa=3)
fafik.Przedstaw()
fafik.Konczyny()
fafik.Wiek()
I'm sorry for asking maybe so stupid question but i truly can't fin solution to my problem.
You're getting the error because you have both a class attribute named Wiek, which in your example is the int 3, and a method called Wiek(), which you try to call on the last line of your example. Since self.Wiek has already been defined as 3, calling fafik.Wiek() is the equivalent of calling fafik.3(), which is invalid.
def Wiek(self):
print('Wiek psa wynosi 6')
self.Wiek = WiekPsa
You have a parameter called Wiek, but also a method called Wiek
When you call fafik.Wiek() python tries to call your parameter Wiek which is an int, and tries to call it as a function which is not possible since it's a int
In any case, don't give a parameter and a function the same name; except for very precise case (getters)
Just rename either the variable Wiek, or the function to a new name and it will work
The problem you have here is that your class has two items having the same name.
An attribute, of type 'int'.
A method.
When you call your function here fafik.Wiek()it understands that you're trying to call the integer attribute as a method.
Just change the name of your function.
O'Reilly's Learn Python Powerful Object Oriented Programming by Mark Lutz teaches different ways to format strings.
This following code has me confused. I am interpreting 'ham' as filling the format place marker at index zero, and yet it still pops up at index one of the outputted string. Please help me understand what is actually going on.
Here is the code:
template = '{motto}, {0} and {food}'
template.format('ham', motto='spam', food='eggs')
And here is the output:
'spam, ham and eggs'
I expected:
'ham, spam and eggs'
The only thing you have to understand is that {0} refers to the first (zeroeth) unnamed argument sent to format(). We can see this to be the case by removing all unnamed references and trying to use a linear fill-in:
>>> "{motto}".format("boom")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'motto'
You would expect that 'boom' would fill in 'motto' if this is how it works. But, instead, format() looks for a parameter named 'motto'. The key hint here is the KeyError. Similarly, if it were just taking the sequence of parameters passed to format(), then this wouldn't error, either:
>>> "{0} {1}".format('ham', motto='eggs')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
Here, format() is looking for the second unnamed argument in the parameter list - but that doesn't exist so it gets a 'tuple index out of range' error. This is just the difference between the unnamed (which are positionally sensitive) and named arguments passed in Python.
See this post to understand the difference between these types arguments, known as 'args' and 'kwargs'.
When I try the following wrong code:
not_float = [1, 2, 3]
"{:.6f}".format(not_float)
I get the following misleading ValueError:
ValueError: Unknown format code 'f' for object of type 'str'
It is misleading, since it might make me think not_float is a string. Same message occurs for other non_float types, such as NoneType, tuple, etc. Do you have any idea why? And: should I expect this error message no matter what the type of non_float is, as long as it does not provide some formatting method for f?
On the other hand, trying:
non_date = 3
"{:%Y}".format(non_date)
brings
ValueError: Invalid conversion specification
which is less informative but also less misleading.
The str.format() method, and the format() function, call the .__format__() method of the objects that are being passed in, passing along everything after the : colon (.6f in this case).
The default object.__format__() implementation of that method is to call str(self) then apply format() on that result. This is implemented in C, but in Python that'd look like:
def __format__(self, fmt):
return format(str(self), fmt)
It is this call that throws the exception. For a list object, for example:
>>> not_float.__format__('.6f')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'f' for object of type 'str'
because this is functionally the same as:
>>> format(str(not_float), '.6f')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'f' for object of type 'str'
Integers have a custom .__format__ implementation instead; it does not use str() internally because there are integer-specific formatting options. It turns the value into a string differently. As a result, it throws a different exception because it doesn't recognize %Y as a valid formatting string.
The error message could certainly be improved; an open Python bug discusses this issue. Because of changes in how all this works the problem is no longer an issue in Python 3.4 though; if the format string is empty .__format__() will no longer be called.
Here's the segment of relevant code:
class MainPage(webapp2.RequestHandler):
def write_form(self,text=""):
self.response.out.write(form%{"text":escape_html(text)}) #form is a html form
def get(self):
self.write_form()
def post(self):
user_input = self.request.get('text') #from a html form
encode = user_input.encode('rot13')
self.write_form(encode)
When write_form is defined, we set the default value of text to be the empty string, I understand this.
Where I'm confused is the last line self.write_form(encode)we're not explicitly stating that we are now setting the variable text to encode (or whatever we want to pass in...).
Does this mean that as we only have one variable (not counting self) that whatever I pass in python will assume it to be what I am passing in for 'text'?
Thanks in advance
Update
Using jamylak's answer, I tried it for myself (python 2.7 as I don't use 3) in a simplified version to get my answer. For n00bs like me this might make the answer a bit clearer:
def example(result="42"):
print result
example()
>>>42
example(87)
>>>87
example("hello")
>>>"hello"
Yes, self is passed implicitly when you call the method of an instance and default arguments need not always be specified with their names(if passed in the correct order). On a side note python 3 allows you to use the asterisk (*) to make sure that you pass them with their names:
>>> def foo(*, text=''):
pass
>>> foo('aa')
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
foo('aa')
TypeError: foo() takes 0 positional arguments but 1 was given
>>>
>>> foo(text='aaa')
your first argument is self which is passed to that function automatically by python. Second argument rot13 is passed to text. If you pass a third argument you will get an error.
I am stuck in using multiple parameter through function.
I have two files:
1.py
import function
x=2
y=5
print function.power(x,y)
function.py
import math
def power(*x)
return math.pow(x,x)
Whenever i try to pass multiple parameter to power function, it is giving following error:
Traceback (most recent call last):
File "C:\Examples\1.py", line 33, in
print function.power(x,y)
File "c:\Examples\function.py", line 11, in power
return math.pow(x,x)
TypeError: a float is required
I think you want:
def power(*x):
return math.pow(*x)
This is a form of argument unpacking. within the power function, x is a tuple which can then be unpacked when passed to another function.
that's because *x is actually making x a list.
You really want to make function.py be:
import math
def power(*x)
return math.pow(x[0],x[1])
Why do you really want to know how to do this though? It obviously can't be to pointlessly wrap the math.pow function.