我希望定义一个类,并使用__repr__
方法,以只写出所有非方法属性的名称和值。我该如何做?我已经将其编写为以下形式,但我意识到这不检查属性类型。
class Example:
def __repr__(self):
return "\n".join(["%s: %s" % (x, getattr(self, x)) for x in dir(self) if not x.startswith('__')])
这里缺少对属性类型的检查。
我希望定义一个类,并使用__repr__
方法,以只写出所有非方法属性的名称和值。我该如何做?我已经将其编写为以下形式,但我意识到这不检查属性类型。
class Example:
def __repr__(self):
return "\n".join(["%s: %s" % (x, getattr(self, x)) for x in dir(self) if not x.startswith('__')])
from inspect import ismethod,getmembers
class Example:
def __repr__(self):
return "\n".join("%s: %s" % (k, v) for (k,v) in getmembers(self,lambda x: not ismethod(x)))
def method(self):
return 1
a = Example()
a.foo = 'bar'
print a
__module__
,__doc__
)。如果您不想要它们,可以相当容易地将其过滤掉。@property
和类变量。 - kennytm__slots__
,你也可以直接迭代实例的__dict__
(或通过vars()
函数)来完成。class Superclass:
def __init__(self, w):
self.w = w
class Example(Superclass):
def __init__(self, x, y, z):
super().__init__(1234)
self.x = x
self.y = y
self.z = z
@property
def x_prop(self):
return self.x
@classmethod
def do_something(cls, z):
return str(cls) + str(z)
def __call__(self):
return 4444
class_property = 42
def __repr__(self):
return "\n".join("%s: [%s]" % (k, v) for (k,v) in vars(self).items())
example = Example(2, lambda y: z, '4')
example2 = Example(example, 6j, b'90')
print(repr(example2))
这将打印
x: [x: [2]
y: [<function <lambda> at 0x7f9368b21ef0>]
z: [4]
w: [1234]]
y: [6j]
z: [b'90']
w: [1234]
e = Example(); e.foo = lambda x:x*x
。 - mgilson