2017-06-09 42 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)