diff --git a/.gitignore b/.gitignore index 6769e21..2dc53ca 100644 --- a/.gitignore +++ b/.gitignore @@ -157,4 +157,4 @@ cython_debug/ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ \ No newline at end of file +.idea/ diff --git a/src/middle-earth/repr.py b/src/middle-earth/repr.py deleted file mode 100644 index 92c05f6..0000000 --- a/src/middle-earth/repr.py +++ /dev/null @@ -1,17 +0,0 @@ -class MyCoolClass: - def __init__(self, *, value: int) -> None: - self.value = value - - def __repr__(self) -> str: - """Repr prints the python code to create this python object.""" - return f"MyCoolClass(value={self.value!r})" - - -if __name__ == "__main__": - my_class = MyCoolClass(value=10) - - class_repr = repr(my_class) - - print("The repr is:", class_repr) - # Evaling the repr should give us an identical object. - print("The evaled repr is:", repr(eval(class_repr))) diff --git a/src/middle-earth/str_and_repr.py b/src/middle-earth/str_and_repr.py new file mode 100644 index 0000000..8e46fe4 --- /dev/null +++ b/src/middle-earth/str_and_repr.py @@ -0,0 +1,32 @@ +import re + + +class MyCoolClass: + def __init__(self, value: str) -> None: + self.value = value + + def __repr__(self) -> str: + return f"MyCoolClass(value={self.value!r})" + + def __str__(self) -> str: + return f"My Cool Class Value is: {self.value}" + + +if __name__ == "__main__": + my_class = MyCoolClass(value="∫ f(x) dx") + print("Printing the output from __repr__()") + print("The repr is:", repr(my_class)) + print(f"Calling the repr using f-string: {my_class!r}") + print("The evaled repr is:", repr(eval(repr(my_class)))) + + print(repr(re.compile(r"\d"))) # Can't eval repr in these examples + o = object() + print(repr(o)) + + print("The ascii repr of my_class is:", ascii(my_class)) + print(f"Calling the ascii using f-string: {my_class!a}\n") + + print("Printing the output from __str__()") + print(my_class) + print("The str() output is:", str(my_class)) + print(f"Calling the str using f-string: {my_class!s} == {my_class}")