My apologies once again for asking another very junior question. For one reason or another, I can’t yet seem to make the transition from Java to Python. I realize that Python has these built in methods that help the user do things. But I was wondering if the two following pieces of code are the same or if one is “more formal” in the sense that it is more commonly used in Java than the other.
def print()
print "My name is___"
and
def _str_()
print "My name is___"
Once again, either one of my methods might be completely wrong (my guess would be the “str” methods. In the interest of time, I have not written out the class name and other methods/attributes. Thanks ahead of time.
You shouldn’t define
printbecause it’s a keyword/built-in function.The
__str__function is used in classes. When an instance of an object is converted to a string, this function is called. Functions such asprintdo this internally. You can also callstr(my_object_instance).Note the double underscores. A single one, like in the OP, isn’t anything special.
Example (Python interactive):
If you have any questions, leave a comment.