python存储在哪里为str的原始值

时间:2017-08-25 05:13:03

标签: python string subclass

我是python的新手,我有一个简单的问题。

说我创建了str的子类来将所有内容更改为' test':

class Mystr(str):
    def __str__(self):
        return 'test'
    def __repr__(self):
        return 'test'

>>> mystr = Mystr(12345)
>>> print(mystr)
test
>>>
>>> print(mystr + 'test')
12345test

我想要的只是' test',但是 python在哪里存储原始值' 12345' ? 我无法在任何地方找到它。

>>> 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']
检查完毕后,我确实在 getnewargs

中找到了它
>>> mystr.__getnewargs__()
('12345',)

然后我将其更改为:

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

为什么还有12345? python在哪里存储原始值' 12345' ?

Python 3.6.1(v3.6.1:69c0db5,2017年3月21日,18:41:36)[MSC v.1900 64 bit(AMD64)] on win32

2 个答案:

答案 0 :(得分:1)

它存储在self中。 self是您的方法所附加的对象,即字符串。

答案 1 :(得分:0)

每当您将一个参数传递给该类时,就会执行该类本地的内置函数 __ getnewargs __ 。然后,该函数将作为参数传递给类的所有变量初始化,并将它们存储在元组中。

现在,当您尝试使用字符串连接类对象(在您的情况下 mystr )时,包含(' 12345',)的元组将返回其唯一的参数& #39; 12345'然后将其与字符串连接并打印为' 12345test'。

如果您尝试以print(mystr + ' anything')这样的方式进行打印,则会打印出“' 12345”'

有关详细信息,请查看 this screenshot