![](/img/trans.png)
[英]How to initialize attributes calculated from other attributes in python classes
[英]How to output class as nested dictionary with attributes calculated if other attributes are != None
我想要一個具有多個屬性的 class。 我希望它也有辦法將 output 這些屬性作為字典並跳過所有 None 值。 同樣在一個完美的場景中,我希望這個 dict 是嵌套的,但首先要做的是:
class MyClass():
def __init__(self, a=False, b=None, c=None, ...):
self.a = a
self.b = b
self.c = c
...
@property
def dictionary(self):
dictionary = { k:v for k, v in self.__dict__.items() if v != None }
return dictionary
這很好用,但是問題是當試圖在字典中包含 self.a + self.b if.= None 的結果時。 __dict__
僅輸出屬於__init__
一部分的值。 我試圖通過使用附加屬性然后使用 setter 來解決這個問題:
class MyClass():
def __init__(self, a=False, b=None, c=None, ... , _var=None):
self.a = a
self.b = b
self.c = c
...
self.var = None
@property
def _var(self):
_var = None
return self.var
@_var.setter
def _var(self):
if self.a & self.b != None:
self.var = self.a + self.b
return self.var
@property
def dictionary(self):
dictionary = { k:v for k, v in self.__dict__.items() if v != None }
return dictionary
不幸的是,當我創建實例時,這並沒有初始化。它甚至可以完成嗎? 我想我看錯了,但不知何故__dict__
似乎是正確的方法。 我對 OOP 很陌生,所以這對我來說都是新的。 先感謝您!
似乎不需要二傳手; 只需將您的條件放入吸氣劑本身:
@property
def var(self):
if self.a is not None and self.b is not None:
return self.a + self.b
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.