Python Forum

Full Version: question about __repr__ in a class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi
the below code is in:https://realpython.com/python-mutable-vs...om-classes

class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y

    @property
    def x(self):
        return self._x

    @property
    def y(self):
        return self._y

    def __repr__(self):
        return f"{type(self).__name__}(x={self.x}, y={self.y})"
what does the last line do also what does the __repe__ method do? how can i use the __repr__ method? if it is omitted, does it cause any problems?
thanks
Objects have two string representations: __str__ is the pretty one, and __repr__ is the smart one. __str__ is used when you call str() or print() an object. __repr__ is used when you call repr() or when you print an object as part of a collection (list, dictionary, set, tuple).

Have you tried omitting the method to see what happens? What do you think will happen?
Don't forget to use the search field in the Python documentation
(Jan-11-2024, 12:14 PM)deanhystad Wrote: [ -> ]Objects have two string representations: __str__ is the pretty one, and __repr__ is the smart one. __str__ is used when you call str() or print() an object. __repr__ is used when you call repr() or when you print an object as part of a collection (list, dictionary, set, tuple).

Have you tried omitting the method to see what happens? What do you think will happen?

hi
i omitted it, but i did not see any change. what can i write or add to the above code too see the changes occure with ommitting the __repr__ method?
thanks again for reply
If the method __str__ is not available, then __repr__ is called instead.

If you just want a class with some variables and a nice representation, you could use dataclasses instead:
import math
from dataclasses import dataclass


@dataclass
class PointD:
    x: int
    y: int

    @property
    def alpha(self):
        """
        alpha for polar coordinates
        """
        return math.degrees(math.atan2(self.y, self.x))

    @property
    def hypot(self):
        """
        Length of hypot
        """
        return math.hypot(self.x, self.y)

    @property
    def polar(self):
        """
        Poloar coordinates
        """
        return self.alpha, self.hypot

    @classmethod
    def from_ploar(cls, polar):
        """
        Create a point from ploar coordinates

        polar := (alpha, hypot)
        """
        alpha = math.radians(polar[0])
        return cls(math.cos(alpha) * polar[1], math.sin(alpha) * polar[1])


p2 = PointD(7, 9)
print(p2)
print(f"{p2!s}")
print(f"{p2!r}")
print(f"{p2.alpha}")
print(f"{p2.hypot}")
print(f"{p2.polar}")
print(PointD.from_ploar(p2.polar))
Output:
PointD(x=7, y=9) PointD(x=7, y=9) PointD(x=7, y=9) 52.1250163489018 11.40175425099138 (52.1250163489018, 11.40175425099138) PointD(x=6.999999999999998, y=9.0)