Here is an example:
def __str__(self):
return f'({self.self.country},{self.self.code},{self.self.product}, {self.cost},{self.quantity })'
This way, when you assign values to a class, you can print its string representation
print(new_shoe)
More info here https://www.pythontutorial.net/python-oop/python-str/
Answer from ssanga on Stack OverflowIn what cases do you use the str() function?
What does __str__ method do?
python - How to use __str__ function to return a string representation of a class - Stack Overflow
What Are The Differences Between __str__ and __repr__ In Class Methods?
Title. I know you use it for integers, but in what context? Also, is it used for anything else?
I'm still a beginner in python and my English is not really good, so I may have a little bit of understanding the explanation given in my course.
So I have this code:
class Apple:
def __init__ (self,color,flavor):
self.color=color
self.flavor=flavor
def __str__(self):
return "This apple is {} and its flavor is {}".format(self.name,self.flavor)
jonagold=Apple("red","sweet")
print(jonagold)The only purpose I see in using the __str__ method, I don't have to write the method in the print () line. If I changed the __str__ method with:
def say(self):
return "This apple is {} and its flavor is {}".format(self.name,self.flavor)I would just need to type
print(jonagold.say())
And I would get the same answer. What are the other purpose of using __str__? In what situation would I need to use the __str__?
Thank you :)
In Python strings are objects, so that values is the size of the object itself. So this size will always be bigger than the string size itself.
From stringobject.h:
typedef struct {
PyObject_VAR_HEAD
long ob_shash;
int ob_sstate;
char ob_sval[1];
/* Invariants:
* ob_sval contains space for 'ob_size+1' elements.
* ob_sval[ob_size] == 0.
* ob_shash is the hash of the string or -1 if not computed yet.
* ob_sstate != 0 iff the string object is in stringobject.c's
* 'interned' dictionary; in this case the two references
* from 'interned' to this object are *not counted* in ob_refcnt.
*/
} PyStringObject;
From here you can get some clues on how those bytes are used:
len(str)+1bytes to store the string itself;- 8 bytes for the hash;
- (...)
You can find some information about the implementation if python strings in a weblog article by Laurent Luce. Additionally you can browse the source.
The size of string objects depends on the OS and type of machine and some choices. On 64-bit FreeBSD, using unicode for string literals (from __future__ import unicode_literals):
In [1]: dir(str)
Out[1]: ['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__',
'__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split',
'_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
In [2]: import sys
In [3]: sys.getsizeof("")
Out[3]: 52
In [4]: sys.getsizeof("test")
Out[4]: 68
In [7]: sys.getsizeof("t")
Out[7]: 56
In [8]: sys.getsizeof("te")
Out[8]: 60
In [9]: sys.getsizeof("tes")
Out[9]: 64
Every character uses 4 bytes extra in this case.
Calling string on a python list calls the __repr__ method on each element inside. For some items, __str__ and __repr__ are the same. If you want that behavior, do:
def __str__(self):
...
def __repr__(self):
return self.__str__()
You can use a list comprehension to generate a new list with each item str()'d automatically:
print([str(item) for item in mylist])