Created
August 30, 2021 22:16
-
-
Save JnyJny/b16e4c64a50c90d4d471d94d04a85624 to your computer and use it in GitHub Desktop.
PDM Classes 101
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" short module description goes here. | |
Longer module description goes here. | |
""" | |
from typing import List, Union | |
__author__ = "[email protected]" | |
class Example: | |
"""Class level docstring | |
Write something here that will help a caller use this class. | |
""" | |
_default_text: str = "the quick red fox jumped over the lazy brown dog" | |
@classmethod | |
def factory(cls, count: int) -> List["Example"]: | |
"""A short description of this classmethod. | |
A longer discussion of expected arguments, return value and | |
any exceptions raised. | |
""" | |
return [cls() for _ in range(0, count)] | |
def __init__(self, text: str = None) -> None: | |
"""A description of the arguments that a caller needs | |
to supply in order to initialize the object successfully. | |
""" | |
self._edits = 0 | |
self.text = text or self._default_text | |
def __repr__(self) -> str: | |
return "{}(text={!r})".format(type(self).__name__, self.text) | |
def __str__(self) -> str: | |
return f"Edits: {self.edits}\nText: {self.text}" | |
def __eq__(self, other: Union["Example", str]) -> bool: | |
try: | |
return self.text == other.text | |
except AttributeError: | |
pass | |
return self.text == other | |
@property | |
def edits(self) -> int: | |
"""Number of times text attribute has changed.""" | |
try: | |
return self._edits | |
except AttributeError: | |
pass | |
self._edits = 0 | |
return self._edits | |
@property | |
def text(self) -> str: | |
"""A short description of the property. | |
Longer description of property and any exceptions it might raise. | |
""" | |
return getattr(self, "_text", None) | |
@text.setter | |
def text(self, value: text) -> None: | |
if not isinstance(value, str): | |
raise TypeError(f"expected string text attribute, not a {type(value)}") | |
if value != self.text: | |
self._edits += 1 | |
self._text = value | |
def common_words(self, text: str) -> List[str]: | |
"""Returns a list of words common to `text` and `self.text`. | |
text: str | |
returns: List[str] | |
raises TypeError if text is not a string | |
""" | |
try: | |
return list(set(self.text.split()) | set(text.split())) | |
except AttributeError: | |
raise TypeError("unexpected type for text {type(text)}") from None | |
if __name__ == "__main__": | |
e0 = Example("this is a test of the emergency broadcast system") | |
e1 = Example("ebony and ivory live together in perfect harmony") | |
examples = Example.factory(11) | |
breakpoint() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment