我成了AutoRepr
类和decorator
类。。。你知道吗
class AutoRepr:
def __repr__(self):
def _fix(thing):
if isinstance(thing, str):
return f'"{thing}"'
if isinstance(thing, Iterable):
s = str(thing)
if len(s) > 30:
return type(thing)
else:
return s
return thing
props = []
try:
for attr in self.__slots__:
if attr.startswith('_'):
continue
try:
attr_val = getattr(self, attr)
if attr_val:
props.append(f'{attr}={_fix(attr_val)}')
except AttributeError:
pass
except AttributeError:
props = [f'{k}={_fix(v)}'
for k, v in self.__dict__.items()
if not k.startswith('_')]
return f'{type(self).__name__}({", ".join(props)})'
def auto_repr(override_all=False):
def decorator(cls):
repr_defined_in = cls.__repr__.__qualname__.split('.')[0]
if not override_all and repr_defined_in == cls.__name__:
# repr overriden in class. Don't mess with it
return cls
cls.__repr__ = AutoRepr.__repr__
return cls
return decorator
# Example 1
@auto_repr()
class MyClass:
def __init__(self):
self.strength = None
self.weakness = 'cake'
# Example 2
class Another(AutoRepr):
__slots__ = ('num', 'my_list')
def __init__(self):
self.num = 12
self.my_list = [1, 2, 3]
f = MyClass()
print(f)
b = Another()
print(b)
# MyClass(strength=None, weakness="cake")
# Another(num=12, my_list=[1, 2, 3])
在decorator中,我需要检查包装的类__repr__
是在类中被重写还是属于父类。如果__repr__
已被类重写,那么我不希望auto\repr做任何事情,但是,如果不是,那么显然希望auto repr做它该做的事情。我通过比较repr方法通过__qualname__
绑定的类的字符串名,成功地拼凑出一个解决方案,但感觉既便宜又笨重。理想情况下,我希望正确地检查标识if cls is repr_defined_in_cls
。你知道吗
我看到的所有SO问题都只涉及获取类的字符串名称,而不是用于比较的类。有没有更好的方法来获取定义方法的(原始)类?你知道吗
当然,沿着
mro
走,确保你击中的第一个__repr__
不是来自object
:我相信,如果元类使用
__slots__
,这将失败,但那将是一个相当反常的现象。你知道吗编辑:
重新阅读您的需求,您可以做如下操作:
完全取决于您需要的语义。我想你明白要点了。你知道吗
检查类
__dict__
中的"__repr__"
键:相关问题 更多 >
编程相关推荐