如何使用减少每个单个元素的多重设置/取消设置功能

时间:2019-12-04 10:54:46

标签: python python-decorators class-method

考虑到我将要分配和取消分配多个值,我该如何使代码更紧凑

class A:
    def __init__(self,*args,**kwargs):
        self._a = 0
        self._b =0
    def set_a(self):
        self._a = 1
    def set_b(self):
        self._b = 1
    def unset_a(self):
        self._a =0
    def unset_b(self):
        self._b = 0

x=A()
x.set_a() 
print(x._a) # 1
x.unset_a()
print(x._a) # 0

我只想避免编写多个set和unset函数,只需编写一个简单的1函数,即我传递类型(set / unset)以及要定位的变量即可

2 个答案:

答案 0 :(得分:1)

我很想使用字典而不是多个变量来执行以下操作:

class A:
    def __init__(self,*args,**kwargs):
        self._d = {'_a': 0, '_b': 0}
    def set_d_item(self, key, val):
        self._d[key] = val

x=A()
x.set_d_item('_a', 1) 
print(x._d['_a']) # 1
x.set_d_item('_a', 0) 
print(x._d['_a']) # 0

如果您确实需要示例中的属性,则可以使用exec(),但我不建议您执行任意代码:

class A:
    def __init__(self,*args,**kwargs):
        self._a = 0
        self._b =0
    def set_item(self, key, val):
        exec(f'self.{key} = {val}')

x=A()
x.set_item('_a', 1) 
print(x._a) # 1
x.set_item('_a', 0) 
print(x._a) # 0

答案 1 :(得分:1)

您可以使用基于预定义配置的setattr使其更紧凑

class A:
    _a = 0
    _b = 0

    var_config = {
        '_a': {'unset': 0, 'set': 1}, 
        '_b': {'unset': 0, 'set': 1}, 
    }

    def set_var(self, var, action='set'):
        setattr(self, var, self.var_config[var][action])


>>> x = A()
>>> print(x._a)
0

>>> x.set_var('_a') 
>>> print(x._a)
1

>>> x.set_var('_a', action='unset') 
>>> print(x._a)
0