當我的建構式添加了 kwargs 時,如何創建表示?
class Thing:
def __init__(self, a, b, **kwargs):
self.a = a
self.b = b
self.__dict__.update(kwargs)
# def __repr__(self):
# return ???
thing1 = Thing(6, 5, color="red")
uj5u.com熱心網友回復:
假設您的確切場景(即每個引數都按原樣分配給一個屬性),這應該有效:
class Thing:
def __init__(self, a, b, **kwargs):
self.a = a
self.b = b
self.__dict__.update(kwargs)
def __repr__(self):
argnames = self.__init__.__code__.co_varnames[1:self.__init__.__code__.co_argcount]
attrdict = dict(self.__dict__)
args = [repr(attrdict.pop(k)) for k in argnames]
kwargs = [f"{k}={repr(v)}" for k, v in attrdict.items()]
return f"{self.__class__.__name__}({', '.join(args kwargs)})"
thing1 = Thing(6, 5, color="red")
print(repr(thing1))
請注意,它不檢測回圈,它取決于每個屬性值的正確表示。
當然,您也可以通過對引數名稱進行硬編碼來簡化代碼,因為您知道它們:
def __repr__(self):
argnames = ["a", "b"]
# ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/537395.html
標籤:Python哎呀表示
