gpt4 book ai didi

python - 扩展 Python 的内置 Str

转载 作者:太空狗 更新时间:2023-10-29 16:56:42 25 4
gpt4 key购买 nike

我正在尝试对 str 进行子类化,但由于其不可变性而遇到一些困难。

class DerivedClass(str):

def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob

def upper(self):
#overridden, new functionality. Return ob of type DerivedClass. Great.
caps = super(DerivedClass, self).upper()
return DerivedClass(caps + '123')

derived = DerivedClass('a')

print derived.upper() #'A123'
print type(derived.upper()) #<class '__main__.DerivedClass'>
print derived.lower() #'a'
print type(derived.lower()) #<type 'str'>

对于不需要任何新功能的继承方法,例如 derived.lower(),是否有一种简单的 pythonic 方法来返回类型为 DerivedClass 的对象>(而不是 str)?还是我像处理 derived.upper() 那样手动覆盖每个 str.method()?

编辑:

#Any massive flaws in the following?

class DerivedClass(str):
def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob

def upper(self):
caps = super(DerivedClass, self).upper()
return DerivedClass(caps + '123')

def __getattribute__(self, name):
att = super(DerivedClass, self).__getattribute__(name)

if not callable(att):
return att

def call_me_later(*args, **kwargs):
result = att(*args, **kwargs)
if isinstance(result, basestring):
return DerivedClass(result)
return result
return call_me_later

最佳答案

类装饰器的良好用途——大致(未经测试的代码):

@do_overrides
class Myst(str):
def upper(self):
...&c...

def do_overrides(cls):
done = set(dir(cls))
base = cls.__bases__[0]
def wrap(f):
def wrapper(*a, **k):
r = f(*a, **k)
if isinstance(r, base):
r = cls(r)
return r
for m in dir(base):
if m in done or not callable(m):
continue
setattr(cls, m, wrap(getattr(base, m)))

关于python - 扩展 Python 的内置 Str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/835469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com