我希望能够将值赋给类的属性,而不必指定它们。
我想做什么
(一)


class HoldingStuff(object):

    def __init__(self, **args):
        self.a = 1
        self.b = '1'
        self.c = 2
        self.d = '3'
        self.e = 4
        for arg in args:
            self[arg] = args[arg]

first = HoldingStuff(a=5)
second = HoldingStuff(d=2, e='2')


当然,我可以在类中使用保存值的字典。但是,这有一个很大的缺点,因为我不能使用代码完成特性。这使得它们很难再利用和找到。(属性是模拟的可变参数的广泛列表。)
什么有用(而且不实际)
(二)

class HoldingStuff(object):

    def __init__(self, **args):
        self['a'] = 1
        self['b'] = '1'
        self['c'] = 2
        self['d'] = '3'
        self['e'] = 4
        for arg in args:
            self[arg] = args[arg]

什么工作
(三)

class HoldingStuff(MutableMapping):

    def __init__(self, **args):
        self.a = 1
        self.b = '1'
        self.c = 2
        self.d = '3'
        self.e = 4
        for arg in args:
            self[arg] = args[arg]

    def __setitem__(self, k, v) -> None:
        if k =='a':
            self.a = v
        elif k =='b':
            self.b = v
        elif k =='c':
            self.c = v
        elif k =='d':
            self.d = v
        elif k =='e':
            self.e = v
        else:
            print(k, "Not available for class.")

    def __delitem__(self, v) -> None:
        pass

    def __getitem__(self, k) -> _VT_co:
        if k =='a':
            return self.a
        elif k =='b':
            return self.b
        elif k =='c':
            return self.c
        elif k =='d':
            return self.d
        elif k =='e':
            return self.e
        else:
            print(k, "Not available for class.")

    def __len__(self) -> int:
        return 5

    def __iter__(self):
        print("Not implemented")

功能__setitem____getitem__似乎是明显和重复的!
问题
有没有办法减少示例C)的源代码,使其以示例a的隐式方式工作?

最佳答案

使用setattr

for name, value in args.items():
    setattr(self, name, value)

关于python - python对象中的隐式项目分配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58391282/

10-12 16:56