![](/img/trans.png)
[英]How to define a class attribute by other attributes of the same class using "attrs"
[英]How best to initialize a class using an attribute from attrs?
在 vanilla Python 中創建一個 class ,它在啟動時也會啟動另一個 class 我將使用__init__(self)
:
class SomeClass:
__init__(self, token: str):
self.token = token
client = WebClient(auth=self.token)
但是在attrs中,我不能這樣做。 以下會產生錯誤,因為它傳遞的是_CountringAttr
object,而不是解析的字符串。
@attr.s()
class SomeClass:
token: str = attr.ib()
client = WebClient(auth=token)
完成此任務的“正確”方法是什么?
您可以使用默認值:
@attr.define
class SomeClass:
token: str
client: WebClient = attr.field() # needed! attr.ib works too
@client.default
def _client_factory(self):
return WebClient(self.token)
或__attrs_post_init__
:
@attr.define
class SomeClass:
token: str
client: WebClient = attr.field(init=False)
def __attrs_post_init__(self):
self.client = WebClient(self.token)
PS 我正在使用現代的attrs
API 來讓它們更廣為人知。 如果您想了解更多信息,請查看https://www.attrs.org/en/latest/names.html 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.