Where is the python storage source value for str

I am new to python and I have a simple question.

Say I'm subclassing str to change everything in 'test':

class Mystr(str): def __str__(self): return 'test' def __repr__(self): return 'test' >>> mystr = Mystr(12345) >>> print(mystr) test >>> >>> print(mystr + 'test') 12345test 

all I want is a β€œtest”, but where does python store the original value of β€œ12345”? I can’t find anything.

 >>> dir(mystr) ['__add__', '__class__', '__contains__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] 

after checking this, I really find it in getnewargs

 >>> mystr.__getnewargs__() ('12345',) 

then I change this to:

 class Mystr(str): def __str__(self): return 'test' def __repr__(self): return 'test' def __getnewargs__(self): return 'test' >>> mystr = Mystr(12345) >>> print(mystr) test >>> mystr.__getnewargs__() 'test' >>> print(mystr + 'test') 12345test 

why is 12345 still there? where does python store the original value "12345"?

Python 3.6.1 (v3.6.1: 69c0db5, March 21, 2017 6:41:36 PM) [MSC v.1900 64 bit (AMD64)] on win32

+5
source share
2 answers

It is stored in self . self is the object your method is attached to, i.e. line.

+1
source

Whenever you pass an argument to a class, the built-in __ getnewargs __ function belonging to the class is executed. The function then initializes all the variables passed to the class as arguments and stores them in the tuple.

Now, when you try to combine a class object, in your case mystr , with a string, the tuple containing ('12345',) returns its only argument, '12345', which is then concatenated with the string and printed as β€œ12345test”.

If you try to print it this way print(mystr + ' anything') , it will print "12345 anything"

For more information, refer to this screenshot.

0
source

Source: https://habr.com/ru/post/1271215/


All Articles