【发布时间】:2019-12-05 11:22:21
【问题描述】:
我想显示一个实例的所有可访问属性的列表,所以我试试这个
class Test:
a=2 #initializing some attribute
b=1 #initializing some attribute
def some_method(self):
attr=[]
for k in [i for i in dir(self) if not i.startswith('__')]:
attr.append(f'{k}={getattr(self,k)}') #to collect all attributes and their values pair
return attr
def __repr__(self): #because i want to overload print behavior
return str(self.some_method())
some_instance=Test()
print(some_instance)
它返回了一个错误:
RecursionError: maximum recursion depth exceeded while calling a Python object
为什么会这样?以及如何解决这个问题?
【问题讨论】:
-
如果你的对象中有一个循环(例如列表包含对
self的引用,或者其中一个元素以某种方式旨在打印self),那么你会进入递归循环。 -
@WillemVanOnsem
a,b,some_method是我在实例中拥有的所有东西,是哪一个导致了这个问题? -
@TuanDoan:通常
dir不仅有这些属性。例如some_method等。Test().some_method的repr(..)是<bond method Test.some_method of repr(self)),因此是递归的,所以Test().some_method的repr(..)会导致对repr(self)的新调用。