String parsing usually means breaking down a string into smaller, meaningful components so you can work with them more easily.
Function chaining means calling multiple functions in sequence so that the output of one becomes the input of the next. It’s a way to build concise, readable pipelines.
Instance Methods
Definition: Regular methods that take self as the first parameter.
Purpose: Operate on a specific object (instance) of the class.
Access: Can access and modify instance attributes (self.name) and class attributes.
Static Methods
Definition: Declared with @staticmethod. They don’t take self or cls as the first parameter.
Purpose: Utility functions that logically belong to the class but don’t need access to instance or class data.
Access: Cannot access self (instance) or cls (class). They are independent.
A static attribute (also called a class attribute) is a variable defined directly inside a class body, outside of any methods. It belongs to the class itself rather than to individual objects, so all instances share the same value unless it’s overridden.
self.words = set() initializes an empty set.
A set automatically removes duplicates, so each word will only appear once.
Take a string (text) as input.
It calls WordSet.cleanText(text) to clean punctuation and lowercase the text.
Then it splits the text into words (text.split() → list of words).
Each word is added into self.words.
Because self.words is a set, duplicates are ignored.
Remove punctuation by chaining .replace() calls:
First removes !, then ., then ,, then '.
Finally, it converts the text to lowercase with .lower().
Example: "Hi, I'm Ryan!" → "hi im ryan"
You create a WordSet object.
You add two sentences.
Each sentence is cleaned, split, and words are stored in the set.
Finally, you print the set of unique words.
This is a class-level (static) attribute.
It belongs to the class WordSet, not to individual objects.
All instances of WordSet share the same list of punctuation marks to remove.
You can access it as WordSet.replacePuncs or wordSet.replacePuncs.
Loops through the static attribute WordSet.replacePuncs.
For each punctuation mark, it removes it from the text using .replace().
Finally, converts the text to lowercase.
Example: "Hi, I'm Ryan!" → "hi im ryan"
The @staticmethod decorator in Python is used to explicitly mark a method as a static method. This makes it clear that the method does not depend on the instance (self) or the class (cls). It’s essentially a utility function that just happens to live inside a class.
Microsoft Copilot
沒有留言:
發佈留言