我想要打印树。因此,问题在于我的RUN输出与DEBUG的输出有所不同,并且在创建DEBUG实例时似乎正在调用__str__
(在DEBUG时变量self.__visited
已被填充)。我在PyCharm工作。
这是用于查找属性的类...
class ListTree:
def __attrnames(self,obj,indent):
spaces=' '*(indent+1)
result=''
for attr in sorted(obj.__dict__):
if attr.startswith('__') and attr.endswith('__'):
result+=spaces+f'{attr}\n'
else:
result+=spaces+f'{attr}={getattr(obj,attr)}\n'
return result
def __listclass(self, aClass, indent):
dots = '.' * indent
if aClass in self.__visited:
return '\n{0}<Class {1}:, address {2}: (see above)>\n'.format(
dots,
aClass.__name__,
id(aClass))
else:
self.__visited[aClass] = True
here = self.__attrnames(aClass, indent)
above = ''
for super in aClass.__bases__:
above += self.__listclass(super, indent + 4)
return '\n{0}<Class {1}, address {2}:\n{3}{4}{5}>\n'.format(
dots,
aClass.__name__,
id(aClass),
here, above,
dots)
def __str__(self):
print('hello world from __str__')
self.__visited = {}
here = self.__attrnames(self, 0)
above = self.__listclass(self.__class__, 4)
return '<Instance of {0}, address {1}:\n{2}{3}>'.format(
self.__class__.__name__,
id(self),
here, above)
这些是要打印的类
class Super():
def __init__(self):
self.data1 = 'spam'
def ham(self):
pass
class Sub(Super, ListTree):
def __init__(self):
Super.__init__(self)
self.data2 = 'eggs'
self.data3 = 42
def spam(self):
pass
instanse = Sub()
print(instanse)
来自RUN的输出是:
hello world from __str__
<Instance of Sub, address 140389925768448:
_ListTree__visited={}
data1=spam
data2=eggs
data3=42
....<Class Sub, address 28451744:
__doc__
__init__
__module__
spam=<function Sub.spam at 0x7faf13a1b670>
........<Class Super, address 28450800:
__dict__
__doc__
__init__
__module__
__weakref__
ham=<function Super.ham at 0x7faf13a1b550>
............<Class object, address 9435264:
DEBUG的输出是:
...
...(lots of repeating hello world from __str__)
...
hello world from __str__
hello world from __str__
hello world from __str__
hello world from __str__
hello world from __str__
hello world from __str__
hello world from __str__
<Instance of Sub, address 140359544124464:
_ListTree__visited={<class '__main__.Sub'>: True, <class '__main__.Super'>: True, <class 'object'>: True, <class '__main__.ListTree'>: True}
data1=spam
data2=eggs
data3=42
....<Class Sub:, address 41729904: (see above)>
>
PyCharm,以及更全局的IntelliJ IDEA IDE,重复地调用本地变量上的字符串转换器以在调试面板中显示其值。
在Python中,此字符串转换器为str
,它调用对象的__str__
方法。如果您的__str__
方法有副作用(例如在stdout
上输出内容),那么这种副作用会发生很多次(至少每次您在调试器中按Next
按钮时,有时会更多)。