Python In Depth Notes

My Python Notes

Just bolting down the things I would like to remember.

General

F-string

x = 1.2000005
f'{x!r}'
f'{x!s}'
f'{x:>+20.6f}'
f'{x:>+20.6e}'

format delegates to str which in turn delegates to repr, so if you don't provide format implementation it will use str if str is not provided either reprwill be used.

Example using class


Class in Python

String Representation of Objects

__repr__ Function

__repr__ (called as dunder repr) basically stands for representation in Python, used to represent(display) code as string.

class Position:

    def __init__(self, latitude, longitude):
        if not (-90 <= latitude <= +90):
            raise ValueError(f'latitude {latitude} is out of range')
        if not (-180<= longitude <= +180):
            raise ValueError(f'{self.__class__.__name__} longitude {longitude} is out of range')

        self.alatitude = latitude
        self.alongitude = longitude

    def __repr__(self):
        return f'{self.__class__.__name__}(Latitude={self.alatitude}, Longitude={self.alongitude})'

India = Position(60, 90)
print(India)

EXPLANATION OF ABOVE EXAMPLE:
i) As in above example a class named 'Position' is created.
ii) A constructor(__init__) is created.
iii) Criteria of input is defined.
iv)__repr__ function is created which diaplays the string in proper format.
OUTPUT:

C:\Users\ashmi\PycharmProjects\Asmi1\venv\Scripts\python.exe C:/Users/ashmi/PycharmProjects/asmi.py/position.py
Position(Latitude=60, Longitude=90)

Process finished with exit code 0

CONVENTIONS FOR GOOD __repr__ RESULTS
i) Include appropriate Objects's State - For smaller objects, it's easy to include all necessary object's state in order to run the function properly. Like in above example, we mentioned class, position and latitude and longitude.
But in case of complex objects, you need to have knowledge to mention only the appropriate objects
ii) Format as Constructor- Your need to format the object so it looks like a constructor call which wouldproduce an object of the same value.