【发布时间】:2020-05-14 12:35:45
【问题描述】:
我想创建一个基类,它具有所有子级都继承的属性,并且还有一个描述性的__repr__ 方法。以下似乎是可接受的实现方式吗?
from collections import Counter
class Component:
cnt = Counter()
def __init__(self, _type, **kwargs):
Component.cnt[_type] += 1
self.type = _type
self.identifier = f'{self.type[0]}{Component.cnt[_type]}'
self._kwargs = kwargs
def __repr__(self):
s = f'{self.__class__.__name__}('
for k, v in self._kwargs.items():
s += f'{k}={v!r}, '
s = s.strip(', ') + f') # identifier: {self.identifier}'
return s
class Battery(Component):
# outbound is positive terminal
def __init__(self, voltage):
super().__init__(self.__class__.__name__, voltage=voltage)
self.voltage = voltage
>>> b=Battery(9)
>>> b
Battery(voltage=9) # identifier: B1
具体来说,self._kwargs 看起来像黑客吗?有什么更好的方法可以做到这一点?或者,有没有比我现在做的更好、更 Python 的方法?
【问题讨论】:
标签: python python-3.x repr