Python: 如何继承str/string?

想搞一个对象继承自str,然后存一些额外信息用来标识这个字符串,然后理所当然地重写了__init__发现跪了:

class newstring(str):
	def __init__(self, value, othervalue):
		str.__init__(self, value)
		self.othervalue = othervalue

astring = newstring('hello', 'othervalue') # Fail

后来发现str的__new__是在__init__前调用的,然后str在__new__的时候发现参数不对就抛了个异常。这么诡异的行为主要是因为str的__new__就返回了个新的实例,而__init__没毛用。Python里面的str大概是这个样子:

class newstring(str):
	def __new__(cls, value):
		return str.__new__(cls, value)
	def __init__(self, value):
		pass

那么想要继承str并在构造时增加一个参数咋整呢,可以重写__new__:

class newstring(str):
	def __new__(cls, value, othervalue):
		return str.__new__(cls, value)
	def __init__(self, value, othervalue):
		self.othervalue = othervalue

或者更简单粗暴的,用*args和**kwargs作为参数重写__new__以绕过__new__的参数检查,然后__init__就可以正常调用了:

class newstring(str):
	def __new__(cls, value, *args, **keywargs):
		return str.__new__(cls, value)
	def __init__(self, value, othervalue):
		self.othervalue = othervalue

然后这样构造的newstring长的跟str一个样,并且可以携带额外信息,有一点需要注意,就是str是个不可变对象,所以newstring构造出来后就别YY能修改它的值了…

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值