Home > Back-end >  Importing methods from built-in class for use in custom class - Python
Importing methods from built-in class for use in custom class - Python

Time:10-29

I created a class with extended methods for the built-in 'str' class, but I want the user to be able to use those normal built-in methods for strings as well as my extra methods. How would I do this without having to manually code each method already in the 'str' class?

class StringMethods:
    """
    StringMethods class:
    
    A class similar to the built in python str class
    but with extended methods for string analysis, password checking etc.
    """
    
    def __init__(self, string: str) -> None:
        
        self.string = string
    
    
    def contains(self, char: str) -> bool:
        
        if char in self.string:
            return True
        return False
    
    
    def containsany(self, chars: str | list | tuple | set) -> bool:
        
        for char in chars:
            if char in self.string:
                return True
        return False
    
    
    def hasdigit(self) -> bool: return self.containsany("0123456789")
    def haslower(self) -> bool: return self.containsany("abcdefghijklmnopqrstuvwxyz")
    def hasupper(self) -> bool: return self.containsany("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    def haswhitespace(self) -> bool: return self.contains(" ")


# I want the user to be able to do the following:
my_string = StringMethods("string123")
print(my_string.hasdigit()) # custom method
print(my_string.upper())    # built-in str method

CodePudding user response:

Here is a class that inherits from str() and is extended with your functions.

class StringMethod(str):
"""
StringMethods class:

A class inheriting from the built in python str class
but with extended methods for string analysis, password checking etc.
"""

def contains(self, char: str) -> bool:
    
    return self.__contains__(char)


def containsany(self, chars: str | list | tuple | set) -> bool:
    
    for char in chars:
        if char in self.__str__():
            return True
    return False


def hasdigit(self) -> bool: return self.containsany("0123456789")
def haslower(self) -> bool: return self.containsany("abcdefghijklmnopqrstuvwxyz")
def hasupper(self) -> bool: return self.containsany("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
def haswhitespace(self) -> bool: return self.contains(" ")

Notice that I dropped the __init__() method as str() provides that already. With this class you can use any builtin string methods plus your own special methods.

  • Related