我做了一个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])
在装饰器中,我需要检查包装的类是否在类中__repr__被覆盖或属于父类。如果__repr__已经被类覆盖,那么我不希望 auto_repr 做任何事情,但是,如果没有,那么显然希望 auto-repr 做它的事情。我设法通过比较通过__qualname__. 理想情况下,我想正确检查身份if cls is repr_defined_in_cls。
我见过的所有 SO 问题都只针对获取类的字符串名称,而不是用于比较的类。有没有更好的方法来获取定义该方法的(原始)类?
12345678_0001
慕容3067478
相关分类