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 OverflowI'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 :)
python - What is doing __str__ function in Django? - Stack Overflow
python - Difference between __str__(self) and show(self) - Stack Overflow
python - def __str__(self): return str(self.name) in model - Stack Overflow
Customize def __str__(self): method when creating a class in Python - Stack Overflow
You created a Blog model. Once you migrate this, Django will create a table with "name" and "tagline" columns in your database.
If you want to interact with the database with the model, for example create an instance of the model and save it or retrieve the model from db,
def __str__(self):
return self.name
will come handy. Open the python interactive shell in your project's root folder via:
python manage.py shell
Then
from projectName.models import Blog
Blog.objects.all() # will get you all the objects in "Blog" table
Also, when you look at the models in your admin panel, you will see your objects listed, with the name property.
The problem is, the return will look like this if you did not add that function:
<QuerySet [<Blog:>,<Blog:>,<Blog:>....]
So you will not know what those objects are. A better way to recognize those objects is retrieving them by one of its properties which you set it as name. This way you will get the result as follow:
<QuerySet [<Blog:itsName>,<Blog:itsName>,<Blog:itsName>....]
If you want to test this out, run python manage.py shell and run:
from projectName.models import Blog
# The below will create and save an instance.
# It is a single step. Copy-paste multiple times.
Blog.objects.create(name="first",tagline="anything")
Blog.objects.all() # check out the result
The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this
Note: how objects are just plainly numbered
to this
.
Note: proper object names here
You could choose what to show in the admin panel, as per your choice. Be it a field value or a default value or something else.
The purpose of having a __str__ method is to create a string representation of the object. __str__ should return a string. If the implementation of __str__ instead printed the string representation and returned nothing, when the object was used in a string context a TypeError will be raised. Take for example:
def __str__(self):
print '%f/%f'%(self.num,self.den)
If we went to display a fraction object like so:
f = Fraction(1,2)
print f
we get an exception:
Traceback (most recent call last):
File "/Users/.../Desktop/...", line 13, in <module>
print f
TypeError: __str__ returned non-string (type NoneType)
>>>
This is because __str__ is used to get the string representation of the object, not print it (by convention that is, you could print as long as you return a string). That's what the print statment/function is used for in conjunction with a __str__ method.
On the other hand a method like show:
def show(self):
print(self.num,"/",self.den) #or even print(self) (for the last part of answer)
Is essentially equivalent to print(f) in the above case (except it includes spaces next to the operands). show is used to output the string representation, while __str__ to get the representation.
However, additional logic may be added to show which isn't appropriate/necessary when constructing a string representation, and hence make sense to have both methods.
You can however use a method like show where a print statement is inappropriate i.e:
if f.show(): pass
if print(f): pass #raise exception
The __str__ method is being very careful to make sure everything is a str and so it returns a str.
The show method is relying on print to convert self.num and self.den to str implicitly. It displays the result as a side-effect, and returns None
print will insert a space between each parameter.
>>> str(3)+"/"+str(5)
'3/5'
>>> print(3,"/",5)
3 / 5
If you don't care about the extra spaces, there's really no reason not to use
def show(self):
print(self)
perhaps the author thinks it's clearer not to do it that way.
Decoupling show and __str__ this way may also be surprising when you try to make a subclass. If the subclass overrides __str__, you would probably expect the change to be reflected in show too.
You should define __str__() method inside the class, also use f strings so:
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=200, null=True, blank=True)
# image =
category = models.CharField(max_length=200, null=True, blank=True)
description = models.TextField(null=True, blank=True)
rating = models.DecimalField(
max_digits=7, decimal_places=2, null=True, blank=True)
numReviews = models.IntegerField(null=True, blank=True, default=0)
price = models.DecimalField(
max_digits=7, decimal_places=2, null=True, blank=True)
countInStock = models.IntegerField(null=True, blank=True, default=0)
createdAt = models.DateTimeField(auto_now_add=True)
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return f"{self.name}"
if your __str__ not work and you receive a Object (1), it mean you use repr(obj). Therefore you should override __repr__ method.
def __repr__(self):
return f'{self.name}'
For this we can use enumerate to easily get the index number of a given element in a list, and with its second argument we can shift it to start from 1, we can use this to get
>>> question = 'Biggest city in England?'
>>> alternatives = ['Manchester', 'Liverpool', 'London']
>>> for i,v in enumerate(alternatives,1):
print(f'{i} - {v}')
1 - Manchester
2 - Liverpool
3 - London
>>>
Now lets change the previous loop into an appropriate list comprehension
>>> [f'{i} - {v}' for i,v in enumerate(alternatives,1)]
['1 - Manchester', '2 - Liverpool', '3 - London']
>>>
Now we use str.join to, well, join them together and remove the [] to make it into a generator expression while we are at it
>>> temp=', '.join(f'{i} - {v}' for i,v in enumerate(alternatives,1))
>>> temp
'1 - Manchester, 2 - Liverpool, 3 - London'
>>>
now we got the 80% of it, lets go for the final touch
>>> f"{question} {temp}"
'Biggest city in England? 1 - Manchester, 2 - Liverpool, 3 - London'
>>>
And we're done.
Also f-string can take almost any python expression, so we can make this into a one liner
>>> f"{question} { ', '.join(f'{i} - {v}' for i,v in enumerate(alternatives,1)) }"
'Biggest city in England? 1 - Manchester, 2 - Liverpool, 3 - London'
>>>
You can try with __str__ as shown below (update the f-string with dashes and/or whitespaces instead of newlines to meet your needs):
>>> class MultipleChoice:
... #Constructor
... def __init__(self, question, alternatives, correct_answer):
... self.question = question
... self.alternatives = alternatives
... self.correct_answer = correct_answer
... def __str__(self):
... return f'{self.question}\n' + '\n'.join(f'{i} {a}' for i, a in enumerate(self.alternatives,1))
...
>>> question1 = MultipleChoice('What´s best?', ['Mac', 'PC'], 1)
>>> question2 = MultipleChoice('Biggest city in England?' , ['Manchester','Liverpool', 'London'], 3)
>>>
>>> print(question1)
What´s best?
1 Mac
2 PC
>>> print(question2)
Biggest city in England?
1 Manchester
2 Liverpool
3 London
Python has two different ways to convert an object to a string: str() and repr(). Printing an object uses str(); printing a list containing an object uses str() for the list itself, but the implementation of list.__str__() calls repr() for the individual items.
So you should also overwrite __repr__(). A simple
__repr__ = __str__
at the end of the class body will do the trick.
Because of the infinite superiority of Python over Java, Python has not one, but two toString operations.
One is __str__, the other is __repr__
__str__ will return a human readable string.
__repr__ will return an internal representation.
__repr__ can be invoked on an object by calling repr(obj) or by using backticks `obj`.
When printing lists as well as other container classes, the contained elements will be printed using __repr__.