2017-06-09 44 views
-3

我有一個python類。我需要通過爲屬性傳遞鍵/值對或通過將在內部解析的編碼字符串來創建實例。使用鍵/值或字符串初始化類實例

這可能嗎?

更新

讓我澄清一下。

class Foo(object): 
    def __init__(self, **kwargs): 
     # This will let me use key/value arguments 

    def __init__(self, data): 
     # This will let me use the whole data as a string 

我想結合這兩個。

我知道,我可以只有一個參數,可以是dictstr,但我不能使用關鍵字參數。

+1

什麼樣的班級?什麼樣的鍵/值對?這可能是可能的,取決於很多因素...... – zwer

回答

0

我覺得你可以,你的問題是有點抽象,所以我的答案是太:

class PythonClass(): 
    def __init__(self, key_value = None, string_to_parse = None): 
    if key_value == None and string_to_parse != None: 
     (key,value) = string_to_parse.decode() #only you know how to extract the values from the string, so I used "decode" method to say something general, but you must use your method 
     self.key = key 
     self.value = value 
    if string_to_parse == None and key_value != None: 
     self.key = key_value[0] 
     self.value = key_value[1] 
1
class A(object): 

    def __init__(self, a): 
     self.x = a**2 
     self.y = a**3 

# initialize directly 
a = A(5) 
print("type: {}, x: {}, y: {}".format(type(a), a.x, a.y)) 
# type: <class '__main__.A'>, x: 25, y: 125 

# initialize with k/v arguments: 
data = {"x": 25, "y": 125} 

b = A.__new__(A) 
b.__dict__.update(data) 
print("type: {}, x: {}, y: {}".format(type(b), b.x, b.y)) 
# type: <class '__main__.A'>, x: 25, y: 125 
+0

爲什麼不'A(**數據)'? –

+0

因爲您需要將類類型作爲第一個參數傳遞,而其他類可以在類本身中被覆蓋。這確保'__dict__'被設置,不管怎樣(幾乎,這個鬼鬼祟祟的開發者也可以部分抽象出__dict__的訪問) – zwer

+0

什麼?不,我的意思是*根本不使用'__new__' * –

1

我不明白爲什麼這是行不通的

class Foo(): 
    def __init__(self, passedDictionary): 
     self.attribute1 = passedDictionary['attribute1_key'] 
     self.attribute2 = passedDictionary['attribute2_key'] 
     .... 

myDict = {"attribute1_key": 5, "attribute2_key": "attribute2_value", ...} 
a = Foo(myDict)