class StringMethods(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:
""" True if self contains specified char """
return char in self
def containsany(self, chars: Iterable) -> bool:
""" True if self contains any specifed chars """
for char in chars:
if str(char) in self:
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(" ")
def removechar(self, char: str) -> "StringMethods":
""" Remove all instances of specified char from self """
return "".join([i for i in self if i != str(char)])
def removechars(self, chars: Iterable) -> "StringMethods":
""" Remove all specified chars from self """
chars = [str(char) for char in chars]
return "".join([i for i in self if str(i) not in chars])
def __sub__(self, subtrahend) -> "StringMethods":
return self[:-subtrahend]
def __add__(self, addend) -> "StringMethods":
return f"{self}{self[-1]}"
y = StringMethods("hello")
y = y.upper() # it is now 'str' type, not 'StringMethods' type
我有自己的擴展 str 類,但我希望用戶能夠繼續使用他們的初始變數作為我的類的實體,但是當他們使用字串方法時,它被轉換為字串而不是 StringMethods()目的。有誰知道我該如何解決這個問題?謝謝
uj5u.com熱心網友回復:
您可以從 繼承,而不是直接str繼承自collections.UserString。
from collections import UserString
class StringMethods(UserString):
"""
StringMethods class:
A class inheriting from the built in python 'str' class,
but with extended methods for string analysis, password checking etc.
"""
...
>>> x = StringMethods("hello")
>>> type(x.upper())
<class '__main__.StringMethods'>
閱讀用戶字串:https ://docs.python.org/3.6/library/collections.html#collections.UserString
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/523027.html
標籤:Python细绳班级遗产
下一篇:從父類實體創建子類實體
