[英]Can you change the string of an instanced string class
I have this class:我有这堂课:
class A(str):
def __str__(self):
return "the string"
def __repr__(self):
return "the repr"
a = A("change me")
Running print a
returns the string
运行print a
返回the string
Running repr(a)
returns the repr
运行repr(a)
返回the repr
Running a
returns change me
经营回报change me
a
Running the instance a
returns the string used to instantiate the class.运行实例a
返回用于实例化类的字符串。 How can I change this string in the instance after instantiation?实例化后如何在实例中更改此字符串?
The returns of __str__
and __repr___
are not the problem, as in certain situations rather than calling these methods the instance is called directly. __str__
和__repr___
的返回不是问题,因为在某些情况下,不是直接调用这些方法,而是直接调用实例。 So where you may expect __repr__
to return, the instance returns the instantiation string instead.因此,在您可能期望__repr__
返回的地方,实例会返回实例化字符串。
I have been unable to find any attributes within the string class to change this.我一直无法在字符串类中找到任何属性来更改它。 Most solutions I've tried require you to re-instance the a
variable, which I don't want to do.我尝试过的大多数解决方案都要求您重新实例化a
变量,我不想这样做。 I want to change the string from within the current instance of the object class variable.我想从对象类变量的当前实例中更改字符串。
I have tried rebuilding the class through methods utilising __new__
and type()
.我尝试通过使用__new__
和type()
的方法来重建类。 However, this seems to require re-instancing the stored class variable, as recreating the class creates a duplicate and does not update the current instance.但是,这似乎需要重新实例化存储的类变量,因为重新创建类会创建一个副本并且不会更新当前实例。
I am limited to using Python 2.7, due to pipeline constraints.由于管道限制,我仅限于使用 Python 2.7。
I have a potential answer, although it feels VERY bad and hacky.我有一个潜在的答案,虽然感觉非常糟糕和hacky。
class A(str):
def __str__(self):
return "the string"
def __repr__(self):
return "the repr"
def _instance_name(self):
return [k for k, v in globals().items() if v is self]
def change(self, new_string):
name = self._instance_name()
if name:
globals()[name[0]] = type('A', (A, ), self.__dict__)(new_string)
a = A("change me")
Running a
returns change me
经营回报change me
a
a.change("I have changed")
Running a
returns I have changed
a
退货I have changed
Changing globals this way feels like welcoming the end times, but it's the only solution I've found so far.以这种方式更改全局变量感觉就像迎接末世,但这是我迄今为止找到的唯一解决方案。 Any other potential methods would be appreciated!任何其他潜在的方法将不胜感激!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.