1. איך אפשר לבנות פונ' שמקבלת שני קלטים אבל בהינתן קלט יחיד היא עדיין תעבוד? ולא תחזיר הודעת error
Date: 27 Nov 2012 21:11
Number of posts: 7
RSS: New posts
Unfortunately, python is a really bad language for this. Most modern languages have a concept called "Method overloading" which lets you define different prototypes for a function with the same name just with different function signature (different parameters types, different number of parameters, different return value type and etc.)
However, because python is a script language that doesn't really compile, there is no type information and therefore it is kinda impossible for python to implement this kind of functionallity.
Therefore, your only option is to do pretty ugly things like defining a constructor gets all the parameters required and you can give default values for them in order to know which parameter was supplied by the caller. And in the function body, you will need to do some checks in order to figure out:
(*) Which parameters were given by the caller
(*) What are the types of the parameters
(*) And of course, as usual, check if they have valid values.
תקנו אותי אם אני טועה:
תמיד אפשר להגדיר פונקציה עם ערך דיפולטי למשל בארגומנט השני,
ואז כשלא מביאים אותו פשוט משתמשים בערך הדיפולטי
ראינו דבר כזה בתרגול
Yes you can do that. Or you can give it a default value that means for you that the caller haven given this parameter a value. It depends exactly on what you want to do.
This post is a good example of how this forum can leverage your Python skills. Although the course team would probably prefer the answers to be less detailed when it comes to specific solutions to HW questions, the posts written here can benefit a lot of students.
A slight correction to the very good answer provided by Random Student on Python not providing a mechanism for method overloading. Everything is accurate, except for the sentence: "Therefore, your only option is to do pretty ugly things like…".
In general, the word "only" is a bit risky. Here, there is at least one more way to solve that problem besides the default value mechanism (this way was also shown in class, and I think it is even more elegant).
But to be clear: the way suggested here is very good and, indeed, solves the problem.
By the words "the course team would probably prefer the answers to be less detailed when it comes to specific solutions to HW questions" I mean that we prefer that the posts will contain hints rather than explicit description of a solution…
Sorry for that. Didn't try to give the solution away. Just wanted to point him to the right direction. That's why I gave him points to think about. But I will try to be in the future less descriptive…
BTW, I think I know what you mean for "other" option but I'm not sure (I won't write here what I think because you said you are afriad it will give the answer away…) So, can you post here what you meant after the HW dead line will pass?