December 2018
Beginner to intermediate
796 pages
19h 54m
English
As you may recall, when you create a class object, Python assigns a name to it. That name acts as a namespace, and sometimes it makes sense to group functionalities under it. Static methods are perfect for this use case since, unlike instance methods, they are not passed any special argument. Let's look at an example of an imaginary StringUtil class:
# oop/static.methods.pyclass StringUtil: @staticmethod def is_palindrome(s, case_insensitive=True): # we allow only letters and numbers s = ''.join(c for c in s if c.isalnum()) # Study this! # For case insensitive comparison, we lower-case s if case_insensitive: s = s.lower() for c in range(len(s) // 2): if s[c] != s[-c -1]: return False return True @staticmethod def get_unique_words(sentence): ...Read now
Unlock full access