簡體   English   中英

向 class 內的字典添加值的 Pythonic 方法

[英]Pythonic way to add values to a dict inside a class

我有一個包含字典的 class 並將其推送到 Cisco APIC:

class Tenant:

    def __init__(self, apic, tenant_name, descr):
        self.apic = apic
        self.tenant_name = tenant_name
        self.descr = descr

        #can this be tidied away?
        self.dn = 'uni/tn-' + tenant_name
        self.rn = 'tn-' + tenant_name

        self.payload = {"fvTenant":{"attributes":{"descr":self.descr,"dn":self.dn,"name":self.tenant_name,"rn":self.rn}}}

'dn' 和 'rn' 的值使用相同的輸入值,除了我分別添加了 'uni/tn-' 和 'tn-' 前綴。

是否有更 Pythonic 的方式將這些值添加到字典中 - 即。 用更少的代碼行?

如果有額外的屬性讓你煩惱,你總是可以在構建字典時只構建“dn”和“rn”的東西

[snip]
   "attributes" : {
      "dn" : "uni/tn-" + tenant_name,
      "rn" : "tn-" + tenant_name,
[snip]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM